-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverse Nodes in k-Group
49 lines (49 loc) · 1.39 KB
/
Reverse Nodes in k-Group
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
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if(k < 2) {
return head;
}
ListNode *result = new ListNode(0);
result->next = head;
ListNode *cur = head, *start = head, *nextP, *preP = result, *head2, *tail;
int count = 0;
while(cur) {
count ++;
if(count == 1) {
//Record the start point of every son list.
head2 = preP;
start = cur;
preP = cur;
if(cur) {
cur = cur->next;
}
}
else if(count == k) {
//Record the next point of every son lists.
tail = cur->next;
cur = start->next;
preP = start;
nextP = cur->next;
while(count > 1) {
cur->next = head2->next;
head2->next = cur;
preP->next = nextP;
cur = nextP;
if(nextP) {
nextP = nextP->next;
}
count --;
}
count = 0;
}
else {
preP = cur;
if(cur) {
cur = cur->next;
}
}
}
return result->next;
}
};