Given the head of a linked list, rotate the list to the right by k places.
Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]
Input: head = [0,1,2], k = 4
Output: [2,0,1]
From: LeetCode
Link: 61. Rotate List
struct ListNode* rotateRight(struct ListNode* head, int k) {
if (head == NULL || k == 0) {
return head;
}
// Step 1: Find the length of the list
int n = 1;
struct ListNode *tail = head;
while (tail->next != NULL) {
n++;
tail = tail->next;
}
// Step 2: Calculate the effective number of rotations needed
k = k % n;
if (k == 0) {
return head;
}
// Step 3: Find the new head and tail
struct ListNode *new_tail = head;
for (int i = 0; i < n - k - 1; i++) {
new_tail = new_tail->next;
}
struct ListNode *new_head = new_tail->next;
// Step 4: Perform the rotation
new_tail->next = NULL;
tail->next = head;
return new_head;
}