forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse-nodes-in-k-group.cpp
45 lines (40 loc) · 1.06 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
// 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:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode dummy{0};
dummy.next = head;
auto curr = head, curr_dummy = &dummy;
int len = 0;
while (curr) {
auto next_curr = curr->next;
len = (len + 1) % k;
if (len == 0) {
auto 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) {
ListNode *first = (*begin)->next;
ListNode *curr = first->next;
while (curr != end) {
first->next = curr->next;
curr->next = (*begin)->next;
(*begin)->next = curr;
curr = first->next;
}
}
};