-
Notifications
You must be signed in to change notification settings - Fork 0
/
sort-list.js
48 lines (37 loc) · 954 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
// Given the head of a linked list, return the list after sorting it in ascending order.
var sortList = function (head) {
if (!head || !head.next) {
return head;
}
let slow = head;
let fast = head.next;
while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
}
let secondHalf = slow.next;
slow.next = null;
let left = sortList(head);
let right = sortList(secondHalf);
return merge(left, right);
};
function merge(left, right) {
let dummy = new ListNode();
let current = dummy;
while (left && right) {
if (left.val < right.val) {
current.next = left;
left = left.next;
} else {
current.next = right;
right = right.next;
}
current = current.next;
}
if (left) {
current.next = left;
} else {
current.next = right;
}
return dummy.next;
};