-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy path143. Reorder List.js
51 lines (48 loc) · 993 Bytes
/
143. Reorder List.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
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {void} Do not return anything, modify head in-place instead.
*/
const reorderList = function (head) {
let sz = 0; let a = head
while (a) sz++, a = a.next
a = head
for (let i = 0; i < Math.floor((sz - 1) / 2); i++) {
a = a.next
}
let head2 = a.next
a.next = null
head2 = reverse(head2)
const dummy = new ListNode()
let p = head; let q = head2; let cur = dummy
while (p || q) {
if (p) {
cur.next = p
p = p.next
cur = cur.next
}
if (q) {
cur.next = q
q = q.next
cur = cur.next
}
}
return dummy.next
}
function reverse (head) {
if (!head) return null
let a = head; let b = a.next
head.next = null
while (b) {
const c = b.next
b.next = a
a = b, b = c
}
return a
}