MEDIUM
Rotate List
Given the head of a linked list, rotate the list to the right by k places.
Example
Input:
head = [1,2,3,4,5], k = 2
[4,5,1,2,3]
Explanation: Rotate the list right by 1: [5,1,2,3,4] Rotate the list right by 2: [4,5,1,2,3]
Constraints
- The number of nodes in the list is in the range [0, 500].
- -100 ≤ Node.val ≤ 100
- 0 ≤ k ≤ 2 * 10^9
Solution: Linked List Manipulation
- Time Complexity: O(n)
- Space Complexity: O(1)
C++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if (!head || !head->next || k == 0) return head;
int n = 1;
ListNode* tail = head;
while (tail->next) {
tail = tail->next;
++n;
}
k = k % n;
if (k == 0) return head;
tail->next = head; // make it circular
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;
}
};