forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rotate-list.cpp
44 lines (40 loc) · 889 Bytes
/
rotate-list.cpp
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
39
40
41
42
43
44
// Time: O(n)
// Space: O(1)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if (head == nullptr || head->next == nullptr) {
return head;
}
int n = 1;
auto curr = head;
for (; curr->next; curr = curr->next) {
++n;
}
curr->next = head;
auto tail = curr;
k = n - k % n;
curr = head;
for (int i = 0; i < k; curr = curr->next, ++i) {
tail = curr;
}
tail->next = nullptr;
return curr;
}
};