Rotate List
Problem
Given the head
of a linked list, rotate the list to the right by k
places.
Solution Approach
Click - to see solution code
- C++
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
ListNode* temp = head;
if (!head) return head;
int n = 1;
while (temp->next) {
n++;
temp = temp->next;
}
if (k % n == 0) return head;
k = k % n;
temp->next = head;
temp = head;
int cnt = 1;
while (cnt < n - k) {
cnt++;
temp = temp->next;
}
ListNode* newhead = temp->next;
temp->next = NULL;
return newhead;
}
};