1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public: ListNode* rotateRight(ListNode* head, int k) { if (k == 0 || !head || !head->next) return head; int n = 1; ListNode* old_tail = head; while (old_tail->next) { old_tail = old_tail->next; ++n; } if ((k %= n) == 0) return head; old_tail->next = head; ListNode* new_tail = head; for (int i = 0; i < n - k - 1; i++) new_tail = new_tail->next; ListNode* new_head = new_tail->next; new_tail->next = nullptr; return new_head; } };
|