1. Description
Given the head of a linked list, return the list after sorting it in ascending order.
2. Example
Example 1

Input: head = [4,2,1,3]
Output: [1,2,3,4]
Example 2

Input: head = [-1,5,3,4,0]
Output: [-1,0,3,4,5]
Example 3
Input: head = []
Output: []
3. Constraints
- The number of nodes in the list is in the range [0, 5 * 10$^4$].
- -10$^5$ <= Node.val <= 10$^5$
4. Solutions
Bottom-Up Merge Sort
n is the number of nodes in the head
Time complexity: O(nlogn)
Space complexity: O(1)
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
| class Solution {
public:
ListNode *sortList(ListNode *head) {
int length = 0;
for (ListNode *iter = head; iter != nullptr; iter = iter->next) {
++length;
}
ListNode dummy(0, head);
for (int len = 1; len < length; len <<= 1) {
ListNode *iter = dummy.next;
ListNode *prev = &dummy;
while (iter != nullptr) {
ListNode *head1 = iter;
ListNode *head2 = split(head1, len);
iter = split(head2, len);
auto [merged_head, merged_tail] = merge_two_lists(head1, head2);
prev->next = merged_head;
merged_tail->next = iter;
prev = merged_tail;
}
}
return dummy.next;
}
private:
ListNode *split(ListNode *head, int len) {
ListNode dummy(0, head);
ListNode *tail = &dummy;
for (; len > 0 && tail->next != nullptr; --len) {
tail = tail->next;
}
ListNode *result = tail->next;
tail->next = nullptr;
return result;
}
pair<ListNode *, ListNode *> merge_two_lists(ListNode *head1, ListNode *head2) {
ListNode dummy;
ListNode *tail = &dummy;
while (head1 != nullptr && head2 != nullptr) {
if (head1->val < head2->val) {
tail->next = head1;
head1 = head1->next;
} else {
tail->next = head2;
head2 = head2->next;
}
tail = tail->next;
}
tail->next = head1 == nullptr ? head2 : head1;
while (tail->next != nullptr) {
tail = tail->next;
}
return {dummy.next, tail};
}
};
|