-
Notifications
You must be signed in to change notification settings - Fork 0
/
061. Rotate List.cpp
58 lines (46 loc) · 1.24 KB
/
061. 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
57
58
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
// Solution 1.
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(!head || !head->next) return head;
int len = 0;
ListNode* p = head;
while(p) p = p->next, len++;
k = k % len;
if(k == 0) return head;
ListNode* slow = head;
ListNode* fast = head;
while(k > 0) fast = fast->next, k--;
while(fast->next) fast = fast->next, slow = slow->next;
ListNode* res = slow->next;
slow->next = NULL;
fast->next = head;
return res;
}
};
// Solution 2.
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(!head || !k) return head;
ListNode* tail(head), *cur(head), *res;
int len = 1;
while(tail->next) tail = tail->next, len++;
k = k % len;
if(!k) return head;
k = len - k;
while(--k) cur = cur->next;
res = cur->next;
cur->next = NULL;
tail->next = head;
return res;
}
};