-
Notifications
You must be signed in to change notification settings - Fork 0
/
025. Reverse Nodes in k-Group.cpp
71 lines (69 loc) · 1.79 KB
/
025. Reverse Nodes in k-Group.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
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
// Solution 1.
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* pre = new ListNode(0);
pre->next = head;
ListNode* res = pre;
ListNode* slow(head), *fast(head), *next;
while(fast){
int i = k - 1;
while(fast && i--) fast = fast->next;
if(fast){
next = fast->next;
reverse(pre, slow, fast, next);
pre = slow;
slow = next;
fast = next;
}
}
return res->next;
}
void reverse(ListNode* left, ListNode* start, ListNode* end, ListNode* right){
ListNode* pre(left), *cur(start), *next;
ListNode* tmp = start;
while(cur != right){
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
left->next = pre;
tmp->next = right;
}
};
// Solution 2.
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode dummy(0);
dummy.next = head;
ListNode* pre = &dummy, *cur(head), *next, *tmp, *p, *ppre, *ccur;
while(cur){
p = cur;
for(int i = 1; i < k && p; i++) p = p->next;
if(!p) break;
ppre = pre;
ccur = cur;
pre = p->next;
tmp = p->next;
while(cur != tmp){
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
ppre->next = pre;
pre = ccur;
}
return dummy.next;
}
};