File tree 2 files changed +50
-0
lines changed
2 files changed +50
-0
lines changed Original file line number Diff line number Diff line change 27
27
22|[ Generate Parentheses] ( ./0022-generate-parentheses.js ) |Medium|
28
28
23|[ Merge k Sorted Lists] ( ./0023-merge-k-sorted-lists.js ) |Hard|
29
29
24|[ Swap Nodes in Pairs] ( ./0024-swap-nodes-in-pairs.js ) |Medium|
30
+ 25|[ Reverse Nodes in k-Group] ( ./0025-reverse-nodes-in-k-group.js ) |Hard|
30
31
26|[ Remove Duplicates from Sorted Array] ( ./0026-remove-duplicates-from-sorted-array.js ) |Easy|
31
32
27|[ Remove Element] ( ./0027-remove-element.js ) |Easy|
32
33
28|[ Implement strStr()] ( ./0028-implement-strstr.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 25. Reverse Nodes in k-Group
3
+ * https://leetcode.com/problems/reverse-nodes-in-k-group/
4
+ * Difficulty: Hard
5
+ *
6
+ * Given the head of a linked list, reverse the nodes of the list k at a time,
7
+ * and return the modified list.
8
+ *
9
+ * k is a positive integer and is less than or equal to the length of the linked
10
+ * list. If the number of nodes is not a multiple of k then left-out nodes, in
11
+ * the end, should remain as it is.
12
+ *
13
+ * You may not alter the values in the list's nodes, only nodes themselves may
14
+ * be changed.
15
+ */
16
+
17
+ /**
18
+ * Definition for singly-linked list.
19
+ * function ListNode(val, next) {
20
+ * this.val = (val===undefined ? 0 : val)
21
+ * this.next = (next===undefined ? null : next)
22
+ * }
23
+ */
24
+ /**
25
+ * @param {ListNode } head
26
+ * @param {number } k
27
+ * @return {ListNode }
28
+ */
29
+ var reverseKGroup = function ( head , k ) {
30
+ const result = new ListNode ( null , head ) ;
31
+ const stack = [ ] ;
32
+ let tail = result ;
33
+
34
+ while ( head ) {
35
+ for ( let i = 0 ; i < k && head ; i ++ ) {
36
+ stack . push ( head ) ;
37
+ head = head . next ;
38
+ }
39
+ if ( stack . length === k ) {
40
+ while ( stack . length ) {
41
+ tail . next = stack . pop ( ) ;
42
+ tail = tail . next ;
43
+ }
44
+ tail . next = head ;
45
+ }
46
+ }
47
+
48
+ return result . next ;
49
+ } ;
You can’t perform that action at this time.
0 commit comments