File tree Expand file tree Collapse file tree 1 file changed +74
-19
lines changed Expand file tree Collapse file tree 1 file changed +74
-19
lines changed Original file line number Diff line number Diff line change 10
10
*/
11
11
class Solution {
12
12
public:
13
+ ListNode* oh=nullptr ;
14
+ ListNode* ot=nullptr ;
15
+
16
+ ListNode* th=nullptr ;
17
+ ListNode* tt=nullptr ;
18
+
19
+ void addfirst (ListNode* node)
20
+ {
21
+ if (th==NULL )
22
+ {
23
+ th=node;
24
+ tt=node;
25
+ }
26
+ else
27
+ {
28
+ node->next =th;
29
+ th=node;
30
+ }
31
+ }
32
+
33
+ int length (ListNode* head)
34
+ {
35
+ int l=0 ;
36
+ ListNode* temp=head;
37
+ while (temp!=NULL )
38
+ {
39
+ l++;
40
+ temp=temp->next ;
41
+ }
42
+
43
+ return l;
44
+ }
45
+
13
46
ListNode* reverseKGroup (ListNode* head, int k) {
14
- auto *initial=head;
15
- ListNode *prevTail=NULL ;
16
- while (head){
17
- ListNode *curr=NULL ,*tail=NULL ;
18
- int count=k;
19
- while (count){
20
- if (!head) return initial;
21
- auto *x=new ListNode (head->val );
22
- x->next =curr;
23
- curr=x;
24
- head=head->next ;
25
- if (!tail) tail=curr;
26
- count--;
47
+ if (head==NULL || head->next ==NULL || k==0 || k==1 ) return head;
48
+
49
+ int len=length (head);
50
+ if (len<k) return head;
51
+
52
+ ListNode* curr=head;
53
+ while (curr!=NULL )
54
+ {
55
+ int tk=k;
56
+
57
+ while (tk-->0 )
58
+ {
59
+ ListNode* fwd=curr->next ;
60
+ curr->next =NULL ;
61
+
62
+ addfirst (curr);
63
+ curr=fwd;
64
+ }
65
+
66
+ len-=k;
67
+
68
+ if (ot==nullptr )
69
+ {
70
+ oh=th;
71
+ ot=tt;
72
+ }
73
+ else
74
+ {
75
+ ot->next =th;
76
+ ot=tt;
77
+ }
78
+ tt=nullptr ;
79
+ th=nullptr ;
80
+
81
+ if (len<k)
82
+ {
83
+ ot->next =curr;
84
+ curr=nullptr ;
27
85
}
28
- if (!prevTail) initial=curr;
29
- else prevTail->next =curr;
30
- prevTail=tail;
31
- tail->next =head;
32
86
}
33
- return initial;
87
+
88
+ return oh;
34
89
}
35
- };
90
+ };
You can’t perform that action at this time.
0 commit comments