-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseNodesink-Group.cpp
More file actions
60 lines (57 loc) · 1.48 KB
/
Copy pathReverseNodesink-Group.cpp
File metadata and controls
60 lines (57 loc) · 1.48 KB
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
#include <vector>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
/* Sol 0
* Recursive solution
*/
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode *p = head;
for(int i = 0;i < k;++i){
if(p == nullptr) return head;
p = p->next;
}
ListNode *pre = reverseKGroup(p,k);
while(k > 0){
ListNode *temp = head->next;
head->next = pre;
pre = head;
head = temp;
--k;
}
return pre;
}
/* Sol 1
* Iteration solution.
* No use of dummy node.
* Use tail to record the last tail whose next pointer need to be modified later.
*/
ListNode* reverseKGroup1(ListNode *head,int k){
int len = 0;
for(ListNode *p=head;p!=nullptr;++len,p=p->next) ;
if(len < k) return head;
ListNode *current = head,*tail = head;
while(len >= k){
ListNode *pre = nullptr,*temp_tail = current;
for(int i = 0;i < k;++i){
ListNode* temp = current->next;
current->next = pre;
pre = current;
current = temp;
}
if(temp_tail == head) head = pre;
else {
tail -> next = pre;
tail = temp_tail;
}
len-=k;
}
tail->next = current;
return head;
}
};