-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.2.ts
44 lines (43 loc) · 1.4 KB
/
index.2.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
import mergeTwoLists from "../merge-two-sorted-lists/index.ts";
import { get_length_of_list } from "../reverse-linked-list-ii/get_length_of_list.ts";
import { ListNode } from "../reverse-linked-list/ListNode.ts";
const sortList = function (head: ListNode | null) {
if (head === null) {
return head;
}
const length = get_length_of_list(head);
const dummyHead = new ListNode(0, head);
for (let subLength = 1; subLength < length; subLength <<= 1) {
let prev = dummyHead,
curr = dummyHead.next;
while (curr !== null) {
const head1 = curr;
for (let i = 1; i < subLength && curr.next !== null; i++) {
curr = curr.next;
}
const head2 = curr.next;
curr.next = null;
curr = head2;
for (
let i = 1;
i < subLength && curr != null && curr.next !== null;
i++
) {
curr = curr.next;
}
let next = null;
if (curr !== null) {
next = curr.next;
curr.next = null;
}
const merged = mergeTwoLists(head1, head2);
prev.next = merged;
while (prev.next !== null) {
prev = prev.next;
}
curr = next;
}
}
return dummyHead.next;
};
export default sortList;