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

Intersection Of Two Linked Lists Problem

LeetCode 160. Given the heads of two singly linked-lists headA...

Sort List Problem

LeetCode 148. Given the head of a linked list, return...

Reorder List Problem

LeetCode 143. You are given the head of a singly...

Linked List Cycle Problem

LeetCode 141. Given head, the head of a linked list,...

Linked List Cycle II Problem

LeetCode 142. Given the head of a linked list, return...

Insertion Sort List Problem

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