-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode_25.cpp
More file actions
33 lines (27 loc) · 768 Bytes
/
Copy pathleetcode_25.cpp
File metadata and controls
33 lines (27 loc) · 768 Bytes
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
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if (!head || k == 1) return head;
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode *prev = dummy, *curr = dummy, *next = dummy;
int count = 0;
while (curr->next) {
curr = curr->next;
count++;
}
while (count >= k) {
curr = prev->next;
next = curr->next;
for (int i = 1; i < k; i++) {
curr->next = next->next;
next->next = prev->next;
prev->next = next;
next = curr->next;
}
prev = curr;
count -= k;
}
return dummy->next;
}
};