Rotate List
Thoughts
Code
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
int n = 0;
auto cur = head;
while (cur != nullptr) {
++n;
cur = cur->next;
}
if (!n) return head;
k = k % n;
if (k == 0) return head;
cur = head;
for (int i = 0; i < n - k - 1; ++i) {
cur = cur->next;
}
auto new_head = cur->next;
cur->next = nullptr;
cur = new_head;
while (cur->next != nullptr) {
cur = cur->next;
}
cur->next = head;
return new_head;
}
};Analysis
Last updated