Skip to content

Commit 227bc62

Browse files
Update 25.cpp
1 parent 04cd2df commit 227bc62

File tree

1 file changed

+74
-19
lines changed

1 file changed

+74
-19
lines changed

leetcode/cpp/linkedlist/25.cpp

Lines changed: 74 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -10,26 +10,81 @@
1010
*/
1111
class Solution {
1212
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+
1346
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;
2785
}
28-
if(!prevTail) initial=curr;
29-
else prevTail->next=curr;
30-
prevTail=tail;
31-
tail->next=head;
3286
}
33-
return initial;
87+
88+
return oh;
3489
}
35-
};
90+
};

0 commit comments

Comments
 (0)