Skip to content

Commit 48da830

Browse files
committed
Add solution #25
1 parent 183fd89 commit 48da830

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
22|[Generate Parentheses](./0022-generate-parentheses.js)|Medium|
2828
23|[Merge k Sorted Lists](./0023-merge-k-sorted-lists.js)|Hard|
2929
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|
3031
26|[Remove Duplicates from Sorted Array](./0026-remove-duplicates-from-sorted-array.js)|Easy|
3132
27|[Remove Element](./0027-remove-element.js)|Easy|
3233
28|[Implement strStr()](./0028-implement-strstr.js)|Easy|
+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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+
};

0 commit comments

Comments
 (0)