-
Notifications
You must be signed in to change notification settings - Fork 0
/
sort-list.js
52 lines (46 loc) · 985 Bytes
/
sort-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
/**
* 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 {ListNode}
*/
var sortList = function(head) {
if (!head || !head.next)
return head;
var slow = head;
var fast = head;
var prev = null;
while (fast && fast.next) {
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
prev.next = null;
return merge(sortList(head), sortList(slow));
};
var merge = function (list1, list2) {
var p1 = list1;
var p2 = list2;
var newHead = new ListNode(0);
var now = newHead;
while (p1 || p2) {
if (!p1 || !p2) {
now.next = p1 || p2;
break;
} else if (p1.val < p2.val) {
now.next = p1;
p1 = p1.next;
} else {
now.next = p2;
p2 = p2.next;
}
now = now.next;
now.next = null;
}
return newHead.next;
};