Skip to main content

0061 - Rotate List (Medium)

https://leetcode.com/problems/rotate-list/

Problem Statement

Given the head of a linked list, rotate the list to the right by k places.

Example 1:

Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]

Example 2:

Input: head = [0,1,2], k = 4
Output: [2,0,1]

Constraints:

  • The number of nodes in the list is in the range [0, 500].
  • -100 <= Node.val <= 100
  • 0 <= k <= 2 * 10^9

Approach 1: Connect and Cut

First we iterate each node till the end and connect the tail to the head. At the same time we calculate how many nodes there, says nn. After that, we find a point to cut the list. The point to cut is nkmodnn - k \mod n. As kk can be greater or equal to nn, so the new head will be located at nkmodnn - k \mod n. Then we link the new tail->next to null and return the new head.

Written by @wingkwong
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if (!head) return NULL;
ListNode *p = head;
int n = 1;
while (p->next) {
p = p->next;
n++;
}
// connect tail to head - like a ring
p->next = head;
// find the location to cut
k = len - k % len;
// move to that location
while (k--) p = p->next;
// p->next is the new head
head = p->next;
// make it as the new tail
p->next = NULL;
// return the new head
return head;
}
};