-
Notifications
You must be signed in to change notification settings - Fork 257
/
reverse-nodes-in-k-group.cpp
49 lines (44 loc) · 1.15 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
46
47
48
49
// Time: O(n)
// Space: O(1)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
* @param head a ListNode
* @param k an integer
* @return a ListNode
*/
ListNode *reverseKGroup(ListNode *head, int k) {
ListNode dummy{0};
dummy.next = head;
auto curr = head, curr_dummy = &dummy;
int length = 0;
while (curr) {
ListNode *next_curr = curr->next;
length = (length + 1) % k;
if (length == 0) {
ListNode *next_dummy = curr_dummy->next;
reverse(&curr_dummy, curr->next);
curr_dummy = next_dummy;
}
curr = next_curr;
}
return dummy.next;
}
void reverse(ListNode **begin, const ListNode *end) {
auto first = (*begin)->next, curr = first->next;
while (curr != end) {
first->next = curr->next;
curr->next = (*begin)->next;
(*begin)->next = curr;
curr = first->next;
}
}
};