Rotate List Problem


Description

LeetCode Problem 61.

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

Example 1:

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

Example 2:

1
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


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
ListNode* rotateRight(ListNode* head, int k) {
    if (!head || !head->next || k == 0) return head;
    ListNode *cur = head;
    int len = 1;
    while (cur->next && ++len) 
        cur = cur->next;
    cur->next = head;
    k = len - k % len;
    while (k--) 
        cur = cur->next;
    head = cur->next;
    cur->next = nullptr;
    return head; 
}




Related Posts

Flatten Binary Tree To Linked List Problem

LeetCode 114. Given the root of a binary tree, flatten...

Remove Duplicates from Sorted List Problem

LeetCode 83. Given the head of a sorted linked list,...

Rotate List Problem

LeetCode 61. Given the head of a linked list, rotate...

Reverse Nodes in k-Group Problem

LeetCode 25. Given a linked list, reverse the nodes of...

Swap Nodes in Pairs Problem

LeetCode 24. Given a linked list, swap every two adjacent...