148. Sort List

题目

https://leetcode.com/problems/sort-list/description/

-w956

想法

归并排序

链表操作比较烦

答案

自己写的一个归并排序,好多地方应该可以优化,不过AC了,就不说什么了:

不过用了递归,这个空间复杂度,恐怕不是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
class Solution {
private:
ListNode *mergeSort(ListNode *head, int len) {
if (len == 1) {
head->next = NULL;
return head;
}
if (len == 2) {
if (head->val <= head->next->val) {
head->next->next = NULL;
return head;
} else {
ListNode *newHead = head->next;
newHead->next = head;
newHead->next->next = NULL;
return newHead;
}
}
int mid = len / 2;
ListNode *p = head;
for (int i = 0; i < mid; i++) {
p = p->next;
}
ListNode *headL = mergeSort(head, mid);
ListNode *headR = mergeSort(p, len - mid);
ListNode dummy(0);
p = &dummy;
while (headL && headR) {
if (headL->val <= headR->val) {
p->next = headL;
headL = headL->next;
} else {
p->next = headR;
headR = headR->next;
}
p = p->next;
}
while (headL) {
p->next = headL;
headL = headL->next;
p = p->next;
}
while (headR) {
p->next = headR;
headR = headR->next;
p = p->next;
}
return dummy.next;
}
public:
ListNode *sortList(ListNode *head) {
if (!head)
return NULL;
int len = 0;
ListNode *p = head;
while (p) {
len++;
p = p->next;
}
ListNode *ret = mergeSort(head, len);
return ret;
}
};