-
Notifications
You must be signed in to change notification settings - Fork 0
/
leetcode-25-Reverse_Nodes_in_k-Group.cpp
64 lines (51 loc) · 1.34 KB
/
leetcode-25-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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
#include <cstdlib>
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if(k==1) return head;
auto temp_pos = head;
auto count_k = k;
while(count_k)
{
if(!temp_pos) return head;
temp_pos = temp_pos->next;
--count_k;
}
auto left = head,
mid = left->next,
right = mid->next;
count_k = (k-1);
while(count_k)
{
left->next = right;
mid->next = head;
head = mid;
mid = right;
right = (right)?right->next:nullptr;
--count_k;
}
auto res = reverseKGroup(mid, k);
left->next = res;
return head;
}
};
int main() {
ListNode* head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5, nullptr)))));
int k = 2;
auto res = Solution().reverseKGroup(head, k);
auto runner = res;
while(runner){
std::cout << runner->val << " ";
runner = runner->next;
}
std::cout << std::endl;
return 0;
}