[LeetCode] Rotate List

61. 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
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
int size = head == nullptr ? 0 : 1;
if(!size)
return head;

ListNode* current = head;
while(current->next != nullptr) {
current = current->next;
size++;
}
current->next = head;

k %= size;

int move = size - k - 1;
current = head;
while(move--) {
current = current->next;
}

head = current->next;
current->next = nullptr;

return head;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/02/11/PS/LeetCode/rotate-list/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.