forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rotate-list.cpp
56 lines (51 loc) · 1.24 KB
/
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
45
46
47
48
49
50
51
52
53
54
55
56
// Time: O(n)
// Space: O(1)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
* @param head: the list
* @param k: rotate to the right k places
* @return: the list after rotation
*/
ListNode *rotateRight(ListNode *head, int k) {
ListNode *dummy_head = new ListNode(INT_MIN);
dummy_head->next = head;
// Get length of the list.
ListNode *cur = dummy_head;
int len = 0;
while (cur->next) {
++len;
cur = cur->next;
}
if (len == 0) {
return nullptr;
}
k %= len;
if (k == 0) {
return head;
}
// Find the position to split.
ListNode *slow = dummy_head;
ListNode *fast = dummy_head;
while (k) {
fast = fast->next;
--k;
}
while (fast && fast->next) {
fast = fast->next;
slow = slow->next;
}
dummy_head->next = slow->next; // New head.
slow->next = nullptr; // Split
fast->next = head; // Link.
return dummy_head->next;
}
};