forked from hijiangtao/LeetCode-with-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathres.ts
65 lines (55 loc) · 1.54 KB
/
res.ts
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
/**
* Definition for singly-linked list.
*/
class ListNode {
val: number
next: ListNode | null
constructor(val?: number, next?: ListNode | null) {
this.val = (val===undefined ? 0 : val)
this.next = (next===undefined ? null : next)
}
}
function merge(start: ListNode | null, end: ListNode | null): ListNode | null {
let result: ListNode | null = new ListNode(0);
let resultPoint = result;
while (start && end) {
if (start.val > end.val) {
resultPoint.next = end;
end = end.next;
} else {
resultPoint.next = start;
start = start.next;
}
resultPoint = resultPoint.next;
}
if (start) {
resultPoint.next = start;
} else {
resultPoint.next = end;
}
return result.next;
}
function sortWithRange(start: ListNode | null, end: ListNode | null): ListNode | null {
if (!start) {
return start;
}
if (start.next === end) {
start.next = null;
return start;
}
let midPoint: ListNode | null = start;
let endPoint: ListNode | null = start;
while(endPoint !== end) {
midPoint = midPoint?.next;
endPoint = endPoint?.next;
if (endPoint !== end) {
endPoint = endPoint?.next;
}
}
const leftNode = sortWithRange(start, midPoint);
const rightNode = sortWithRange(midPoint, end);
return merge(leftNode, rightNode);
}
function sortList(head: ListNode | null): ListNode | null {
return sortWithRange(head, null);
};