-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy path0148_SortList.js
62 lines (61 loc) · 1.51 KB
/
0148_SortList.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
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var sortList = function(head) {
function mergeSort(node){
if(!node || !node.next){
return node;
}
let middle = getMiddle(node);
let next_to_middle = middle.next;
//divide in the middle;
middle.next = null;
let left = mergeSort(node)
let right = mergeSort(next_to_middle);
let merged_list = merge(left,right);
return merged_list;
}
function merge(left,right){
let result = null
if(!left){
return right;
}
if(!right){
return left;
}
if(left.val<=right.val){
result = new ListNode(left.val);
result.next = merge(left.next,right)
} else{
result = new ListNode(right.val);
result.next = merge(left,right.next);
}
return result;
}
function getMiddle(node){
if(!node){
return null
}
let slow = node;
let fast = node.next;
// fast are moving 2 times faster. so when it comes to the end,
// slow will be in the middle
while(fast!=null){
fast = fast.next;
if(fast!=null){
slow = slow.next;
fast = fast.next;
}
}
return slow;
}
return mergeSort(head)
};