File tree Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for singly-linked list.
3
+ * function ListNode(val, next) {
4
+ * this.val = (val===undefined ? 0 : val)
5
+ * this.next = (next===undefined ? null : next)
6
+ * }
7
+ */
8
+ /**
9
+ * @param {ListNode } head
10
+ * @param {number } k
11
+ * @return {ListNode }
12
+ */
13
+ const reverseKGroup = function ( head , k ) {
14
+ let sz = 0
15
+ let a = head
16
+ while ( a ) sz ++ , a = a . next
17
+
18
+ const dummy = new ListNode ( 0 , head )
19
+ // x: dummy, y: 1
20
+ let x = dummy ; let y = dummy . next
21
+ for ( let i = 0 ; i < Math . floor ( sz / k ) ; i ++ ) {
22
+ a = y
23
+ let b = a . next
24
+ // 节点个数为 k,只需要反转 k-1 次中间的边
25
+ for ( let j = 0 ; j < k - 1 ; j ++ ) {
26
+ const c = b . next
27
+ b . next = a
28
+ a = b , b = c
29
+ }
30
+ // dummy -> 2, 1 -> 3
31
+ x . next = a , y . next = b
32
+ // x: 1, y: 3
33
+ x = y , y = y . next
34
+ }
35
+
36
+ return dummy . next
37
+ }
Original file line number Diff line number Diff line change 171
171
172
172
- 206 . Reverse Linked List
173
173
- 92 . Reverse Linked List II
174
+ - 25 . Reverse Nodes in k-Group
174
175
175
176
## Links
176
177
You can’t perform that action at this time.
0 commit comments