forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverse Nodes in k-Group.cpp
54 lines (41 loc) · 1.39 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
50
51
52
53
54
class Solution {
pair<ListNode* , ListNode*> get_rev_list(ListNode* root){
ListNode *tail = root;
ListNode *curr = root , *temp , *prev = NULL;
while(curr != NULL){
temp = curr -> next;
curr -> next = prev;
prev = curr;
curr = temp;
}
return make_pair(prev , tail);
}
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if(k == 1)
return head;
vector<pair<ListNode* , ListNode*>> store;
ListNode *temp = head , *temp_head = head;
int len = 0;
while(temp != NULL){
len++;
if(len == k){
ListNode *next_head = temp -> next;
temp -> next = NULL;
store.push_back(get_rev_list(temp_head));
temp = next_head;
len = 0;
temp_head = next_head;
}
else
temp = temp -> next;
}
if(len == k)
store.push_back(get_rev_list(temp_head));
for(int i = 1; i < store.size(); i++)
store[i - 1].second -> next = store[i].first;
if(len != k)
store[store.size() - 1].second -> next = temp_head;
return store[0].first;
}
};