-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
76 lines (68 loc) · 1.57 KB
/
main.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
71
72
73
74
75
76
/**
* 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) {
// k <= length
const dummy = new ListNode(-1)
dummy.next = head
let start = dummy
let end = dummy
while (true) {
let cnt = 0
while (cnt < k && end != null) {
end = end.next
cnt += 1
}
if (cnt < k || end == null) {
break
}
let nextStart = start.next
for (let _ = 0; _ < k - 1; _++) {
const moving = start.next
start.next = moving.next
moving.next = end.next
end.next = moving
}
start = end = nextStart
}
return dummy.next
}
function ListNode (val) {
this.val = val
this.next = null
}
if (process.env.LZS) {
// local test
const { arrToList, listToArr } = require('../utils')
const assert = require('chai').assert
assert.deepEqual(listToArr(
reverseKGroup(arrToList([1, 3, 4, 5]), 2)
), [3, 1, 5, 4])
assert.deepEqual(listToArr(
reverseKGroup(arrToList([1, 3, 4]), 2)
), [3, 1, 4])
assert.deepEqual(listToArr(
reverseKGroup(arrToList([1, 3, 4, 5]), 4)
), [5, 4, 3, 1])
assert.deepEqual(listToArr(
reverseKGroup(arrToList([1, 3, 4, 5]), 3)
), [4, 3, 1, 5])
assert.deepEqual(listToArr(
reverseKGroup(arrToList([1, 3, 4, 5]), 1)
), [1, 3, 4, 5])
assert.deepEqual(listToArr(
reverseKGroup(arrToList([1, 3, 4, 5]), 0)
), [1, 3, 4, 5])
assert.deepEqual(listToArr(
reverseKGroup(arrToList([1]), 1)
), [1])
}