forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path25-Reverse-Nodes-in-K-Group.js
More file actions
44 lines (36 loc) · 915 Bytes
/
25-Reverse-Nodes-in-K-Group.js
File metadata and controls
44 lines (36 loc) · 915 Bytes
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
/**
* https://leetcode.com/problems/reverse-nodes-in-k-group/
* Time O(N) | Space O(N)
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/
var reverseKGroup = function(head, k) {
const sentinel = tail = new ListNode(0, head);
while (true) {
let [ start, last ]= moveNode(tail, k);
if (!last) break;
reverse([ start, tail.next, start ])
const next = tail.next;
tail.next = last;
tail = next;
}
return sentinel.next;
};
const moveNode = (curr, k) => {
const canMove = () => k && curr;
while (canMove()) {
curr = curr.next;
k--;
}
return [ (curr?.next || null), curr ];
}
const reverse = ([ prev, curr, start ]) => {
const isSame = () => curr === start;
while (!isSame()) {
const next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
}