Rotate List

Posted by Bill on February 21, 2024

Rotate List

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

1
2
3
4
5
6
7
8
9
10
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]

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
  public:
  ListNode* rotateRight(ListNode* head, int k) {
    if (head == nullptr) {
      return nullptr;
    }
    int i = 0;
    ListNode* p = head;
    ListNode* fixHead = head;
    int size = 0;
    ListNode* sizePtr = head;
    while (sizePtr) {
      size++;
      sizePtr = sizePtr->next;
    }
    k = k % size;
    while (i < k) {
      while (p->next != nullptr && p->next->next != nullptr) {
        p = p->next;
      }
      ListNode* prevNode = p;
      ListNode* tailNode = p->next;
      if (tailNode == nullptr) {
        return fixHead;
      }
      p->next = nullptr;
      tailNode->next = fixHead;
      p = tailNode;
      fixHead = p;
      i++;
    }
    return fixHead;
  }
};