-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathReverse-Nodes-in-k-Group.js
64 lines (60 loc) · 1.15 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
//
// Copyright (c) 2018 by liril.net. All Rights Reserved.
//
/**
* 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 <= 0) return head;
let start = {
next: head
};
let begin = start;
let pointer = head;
let i = 0;
while (head) {
if (++i < k) {
head = head.next;
} else {
i = 0;
const next = head.next;
while (pointer.next !== next) {
const temp = pointer.next;
pointer.next = temp.next;
temp.next = begin.next;
begin.next = temp;
}
begin = pointer;
head = next;
pointer = next;
}
}
return start.next;
};
function ListNode(val) {
this.val = val;
this.next = null;
}
const n1 = new ListNode(1);
const n2 = new ListNode(2);
const n3 = new ListNode(3);
const n4 = new ListNode(4);
const n5 = new ListNode(5);
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
let start = reverseKGroup(n1, 6);
while (start) {
console.log(start.val);
start = start.next;
}