-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathindex.js
46 lines (39 loc) · 1020 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* Problem: https://leetcode.com/problems/reverse-nodes-in-k-group/description/
*/
const { ListNode } = require('../util/javascript/problem-utils');
const reverseNodesInKGroup = (list, k) => {
const reverse = (start, end) => {
let tail = null;
let head = new ListNode();
while (start !== end) {
let tmp = start;
start = start.next;
tmp.next = head.next;
head.next = tmp;
if (!tail) tail = tmp;
}
start.next = head.next;
head.next = start;
if (!tail) tail = start;
return [head, tail];
};
let root = list, i = 0;
let start, end;
const result = new ListNode();
let resultTail = result;
while (root) {
if (0 === i % k) start = root;
if (0 === (i + 1) % k) end = root;
i++;
root = root.next;
if (start && end) {
const [head, tail] = reverse(start, end);
resultTail.next = head.next;
resultTail = tail;
start = end = null;
}
}
resultTail.next = start;
return result.next || null;
};