仔细一想,其实还可以再优化时间复杂度,不过要考虑很多边界情况,懒得考虑了:
class Solution { public: ListNode* rotateRight(ListNode* head, int k) { int size = 0; ListNode* p = head; if (!p) return NULL; while (p) { p = p->next; size++; } p = head; k %= size; while (k--) { ListNode* q; while (p != NULL && p->next != NULL) { q = p; p = p->next; } p->next = head; q->next = NULL; head = p; } return head; } };