-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathreverse-nodes-in-k-group.js
70 lines (64 loc) · 1.17 KB
/
reverse-nodes-in-k-group.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
var DEBUG = process.env.DEBUG;
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/
var reverseKGroup = function(head, k) {
if (k === 1) return head;
var p = {
val: null,
next: head
};
var length = 0;
var curr = head;
while (curr) {
length++;
curr = curr.next;
}
var nGroup = Math.floor(length / k);
var groupHead = p, groupTail;
while (nGroup) {
groupTail = forward(groupHead, k);
reverse(groupHead, groupTail);
groupHead = forward(groupHead, k);
nGroup--;
}
return p.next;
};
// head->a->b->c->tail->x ==>
// head->tail->c->b->a->x
function reverse(head, tail) {
var c = head.next;
var prev = head;
while (prev !== tail) {
var tmp = c.next;
c.next = prev;
prev = c;
c = tmp;
}
head.next.next = c;
head.next = tail;
}
function forward(node, step) {
while (step) {
node = node.next;
step--;
}
return node;
}
function test(f) {
[
[[]]
].forEach(function (input) {
console.log(f.apply(undefined, input));
});
}
if (DEBUG) test();