-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathReverseNodesInKGroup.cpp
More file actions
48 lines (42 loc) · 1.21 KB
/
Copy pathReverseNodesInKGroup.cpp
File metadata and controls
48 lines (42 loc) · 1.21 KB
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
/**
* 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) return NULL;
if (k < 2) return head;
ListNode dummy(0);
dummy.next = head;
ListNode *cur = head, *prev = &dummy;
int count = 1;
while (cur) {
ListNode *nxt = cur->next;
if (count % k == 0) {
// The last element of k-reversed-list will be prev for the next k-reversed-list
prev = reverse(prev, cur->next);
}
++count;
cur = nxt;
}
return dummy.next;
}
// Reverse the list until reaching end (adjust to maintain the links of head and tail more easily)
ListNode *reverse(ListNode *prev, ListNode *end) {
ListNode *last = end, *head = prev->next, *cur = head;
while (cur != end) {
ListNode *nxt = cur->next;
cur->next = last;
last = cur;
cur = nxt;
}
prev->next = last;
// Return the last element
return head;
}
};