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

Middle Of The Linked List Problem

LeetCode 876. Given the head of a singly linked list,...

Linked List Components Problem

LeetCode 817. You are given the head of a linked...

Split Linked List In Parts Problem

LeetCode 725. Given the head of a singly linked list...

All O'One Data Structure Problem

LeetCode 432. Design a data structure to store the strings...

Add Two Numbers II Problem

LeetCode 445. You are given two non-empty linked lists representing...