-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathReverse_Nodes_in_k-Group.cpp
45 lines (45 loc) · 1.26 KB
/
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k) {
if(!head or !head->next) return head;
ListNode *sentinel = new ListNode(0);
sentinel->next = head;
int len = 0;
ListNode *prev = sentinel;
ListNode *iter = head;
ListNode *newHead = head;
bool flag = false;
while(iter) {
++len;
if(len == k) {
if(!flag) {
newHead = iter;
flag = true;
}
ListNode *tail = iter;
ListNode *newHead = tail;
ListNode *tmp = head;
while(head != newHead) {
ListNode *nxt = tail->next;
tail->next = head;
head = head->next;
tail->next->next = nxt;
}
prev->next = head;
prev = tmp;
head = prev->next;
len = 0;
}
iter = iter->next;
}
return newHead;
}
};