Skip to content

Commit 05676f5

Browse files
authored
Create 25-reverse-nodes-in-k-group.js
1 parent 5c38a99 commit 05676f5

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

25-reverse-nodes-in-k-group.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val) {
4+
* this.val = val;
5+
* this.next = null;
6+
* }
7+
*/
8+
/**
9+
* @param {ListNode} head
10+
* @param {number} k
11+
* @return {ListNode}
12+
*/
13+
const reverseKGroup = function(head, k) {
14+
let n = 0
15+
for (let i = head; i != null; n++, i = i.next);
16+
let dmy = new ListNode(0)
17+
dmy.next = head
18+
for (let prev = dmy, tail = head; n >= k; n -= k) {
19+
for (let i = 1; i < k; i++) {
20+
let next = tail.next.next
21+
tail.next.next = prev.next
22+
prev.next = tail.next
23+
tail.next = next
24+
}
25+
26+
prev = tail
27+
tail = tail.next
28+
}
29+
return dmy.next
30+
}

0 commit comments

Comments
 (0)