-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseNodesink-Group.cpp
More file actions
116 lines (98 loc) · 1.65 KB
/
ReverseNodesink-Group.cpp
File metadata and controls
116 lines (98 loc) · 1.65 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include<iostream>
using namespace std;
struct ListNode{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL){}
};
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if(head==NULL || head->next==NULL||k==1){
return head;
}
ListNode *p,*q,*last,*r,*s;
p=head;
while(p!=NULL){
int i;
last=p;
s=p;
for(i=0;i<k-1;i++){
s=s->next;
//cout<<"i: "<<i<<"------"<<"s: "<<s->val<<endl;
if(s==NULL){
break;
}
}
cout<<"i: "<<i<<"s: "<<s->val<<endl;
if(i!=k-1){
cout<<"i: "<<i<<endl;
if(last==head){
head=p;
}
break;
}
else{
if(last==head){
head=s;
}
cout<<"head: "<<head->val<<endl;
}
for(int i=0;i<k-1;i++){
if(i==0){
q=p->next;
}
else{
p=q;
q=r;
}
r=q->next;
q->next=p;
//cout<<"p: "<<p->val<<"------"<<"q: "<<q->val<<"------"<<"r: "<<r->val<<endl;
}
cout<<"r: "<<r<<endl;
s=r;
if(s!=NULL){
for(i=0;i<k-1;i++){
s=s->next;
if(s==NULL){
break;
}
}
cout<<"i: "<<i<<endl;
if(i!=k-1){
s=r;
}
}
//cout<<"s: "<<s->val<<"-------"<<"last: "<<last->val<<endl;
last->next=s;
p=r;
}
return head;
}
};
int main(){
int n;
cin>>n;
int num;
cin>>num;
ListNode *head;
ListNode *p=new ListNode(num);
head=p;
for(int i=1;i<n;i++){
cin>>num;
ListNode *q=new ListNode(num);
p->next=q;
p=q;
}
p->next=NULL;
int k;
cin>>k;
Solution *solution=new Solution();
head=solution->reverseKGroup(head,k);
while(head!=NULL){
cout<<head->val<<endl;
head=head->next;
}
return 0;
}