-
Notifications
You must be signed in to change notification settings - Fork 0
/
reorder-list.js
58 lines (47 loc) · 1.13 KB
/
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
52
53
54
55
56
57
58
/**
* 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.
*/
var reorderList = function(head) {
if (!head || !head.next || !head.next.next) return;
// find mid
var mid = null;
var fast = head;
var slow = head;
while (fast.next && fast.next.next && slow.next) {
slow = slow.next;
fast = fast.next.next;
}
mid = slow;
// reverse the later part
var now = mid.next.next;
var second = mid.next;
var tmp = null;
second.next = null;
while (now) {
tmp = now.next;
now.next = second;
second = now;
now = tmp;
}
mid.next = second;
// insert one after another
var before = head;
var after = mid.next;
mid.next = null;
while (after) {
tmp = before.next;
before.next = after;
before = tmp;
tmp = after.next;
after.next = before;
after = tmp
}
};