Skip to content

Commit 6f7b7a0

Browse files
authored
Update 25-reverse-nodes-in-k-group.js
1 parent 056e513 commit 6f7b7a0

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

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

+42
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,48 @@ const reverseKGroup = function(head, k) {
2929
return dmy.next
3030
}
3131

32+
// another
33+
34+
/**
35+
* Definition for singly-linked list.
36+
* function ListNode(val, next) {
37+
* this.val = (val===undefined ? 0 : val)
38+
* this.next = (next===undefined ? null : next)
39+
* }
40+
*/
41+
/**
42+
* @param {ListNode} head
43+
* @param {number} k
44+
* @return {ListNode}
45+
*/
46+
const reverseKGroup = function (head, k) {
47+
if(head == null) return head
48+
const dummy = new ListNode()
49+
dummy.next = head
50+
let n = 0, cur = head
51+
while(cur) {
52+
n++
53+
cur = cur.next
54+
}
55+
if(n < k) return head
56+
let pre = dummy, tail = head
57+
58+
for(let i = 0; i + k <= n; i += k) {
59+
for(let j = 1; j < k; j++) {
60+
const tmp = pre.next
61+
pre.next = tail.next
62+
tail.next = tail.next.next
63+
pre.next.next = tmp
64+
}
65+
pre = tail
66+
tail = tail.next
67+
}
68+
69+
return dummy.next
70+
}
71+
72+
73+
3274
// another
3375

3476
/**

0 commit comments

Comments
 (0)