forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0025-reverse-nodes-in-k-group.cs
58 lines (50 loc) · 1.21 KB
/
0025-reverse-nodes-in-k-group.cs
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
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
publicclassSolution
{
publicListNodeReverseKGroup(ListNodehead,intk)
{
vardummy=newListNode(0,head);
vargroupPrev=dummy;
vargroupNext=dummy;
while(true)
{
varkth=getKth(groupPrev,k);
if(kth==null)
break;
groupNext=kth.next;
// reverse group
varprev=kth.next;
varcurr=groupPrev.next;
while(curr!=groupNext)
{
vartemp=curr.next;
curr.next=prev;
prev=curr;
curr=temp;
}
vartmp=groupPrev.next;
groupPrev.next=kth;
groupPrev=tmp;
}
returndummy.next;
}
privateListNodegetKth(ListNodecurr,intk)
{
while(curr!=null&&k>0)
{
curr=curr.next;
k-=1;
}
returncurr;
}
}