forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0025-reverse-nodes-in-k-group.ts
51 lines (42 loc) · 1.1 KB
/
0025-reverse-nodes-in-k-group.ts
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
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
functionreverseKGroup(head: ListNode|null,k: number): ListNode|null{
letdummy=newListNode(0,head);
letgroupPrev=dummy;
while(true){
letkth=getKth(groupPrev,k);
if(!kth){
break;
}
letgroupNext=kth.next;
// reverse group
letprev=kth.next;
letcurr=groupPrev.next;
while(curr!==groupNext){
lettemp=curr.next;
curr.next=prev;
prev=curr;
curr=temp;
}
lettemp=groupPrev.next;
groupPrev.next=kth;
groupPrev=temp;
}
returndummy.next;
}
functiongetKth(curr: ListNode|null,k: number): ListNode|null{
while(curr&&k>0){
curr=curr.next;
k-=1;
}
returncurr;
}