-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
62 lines (60 loc) · 1.26 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
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var sortList = function(head) {
if (!head || !head.next) {
return head;
}
let fast = head;
let slow = head;
let pre = head;
while (fast && fast.next) {
pre = slow;
fast = fast.next.next;
slow = slow.next;
}
pre.next = null;
const left = sortList(head);
const right = sortList(slow);
return merge(left, right);
};
function merge(left, right) {
let result = new ListNode(-1);
let cur = result;
while (left && right) {
if (left.val > right.val) {
cur.next = right;
right = right.next;
} else {
cur.next = left;
left = left.next;
}
cur = cur.next;
}
while (left) {
cur.next = left;
cur = cur.next;
left = left.next;
}
while (right) {
cur.next = right;
cur = cur.next;
right = right.next;
}
return result.next;
}
module.exports = {
id:'148',
url:'https://leetcode.com/problems/sort-list/',
difficulty:'medium',
title:'Sort List',
have_md:true,
};