-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
86 lines (71 loc) · 2.02 KB
/
index.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var sortList = function(head) {
function sort(head){
let node = head;
let last;
if(head === null || head.next === null) return head;
let fast = head;
let slow = head;
if(head.next === null) return head;
if(head.next.next === null){
if(head.val > head.next.val){
let t = head.val;
head.val = head.next.val;
head.next.val = t;
}
return head;
}
while(fast && fast.next !== null){
fast = fast.next.next;
slow = slow.next;
}
fast = slow;
slow = slow.next;
fast.next = null;
let node1 = sort(head);
let node2 = sort(slow);
return merge(node1, node2);
}
function merge(node1, node2){
let head = null;
if(node1.val < node2.val){
head = new ListNode(node1.val);
node1 = node1.next;
}else{
head = new ListNode(node2.val);
node2 = node2.next;
}
let node = head;
while(node1 || node2){
if(node1 === null){
node.next = node2;
node = node.next;
node2 = node2.next;
}else if(node2 === null){
node.next = node1;
node = node.next;
node1 = node1.next;
}else if(node1.val < node2.val){
node.next = node1;
node = node.next;
node1 = node1.next;
}else{
node.next = node2;
node = node.next;
node2 = node2.next;
}
}
return head;
}
return sort(head);
};