diff --git a/61. Rotate List.cpp b/61. Rotate List.cpp new file mode 100644 index 0000000..e531875 --- /dev/null +++ b/61. Rotate List.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + ListNode* rotateRight(ListNode* head, int k) { + if (!head || !head->next || k == 0) + return head; + + ListNode* tail; + int length = 1; + for (tail = head; tail->next; tail = tail->next) + ++length; + tail->next = head; // Circle the list + + const int t = length - k % length; + for (int i = 0; i < t; ++i) + tail = tail->next; + ListNode* newHead = tail->next; + tail->next = nullptr; + + return newHead; + } +};