-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsort-list.cc
64 lines (50 loc) · 1.08 KB
/
sort-list.cc
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
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *middleNode(ListNode *head) {
if (head == NULL) return NULL;
ListNode *fast = head, *slow = head;
while (fast->next && fast->next->next) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
ListNode *merge(ListNode *a, ListNode *b) {
if (a == NULL) return b;
if (b == NULL) return a;
ListNode *head = NULL, *tail = NULL;
while (a && b) {
ListNode **p;
if (a->val <= b->val) {
p = &a;
} else {
p = &b;
}
if (head == NULL) {
head = *p;
} else {
tail->next = *p;
}
tail = *p;
*p = (*p)->next;
}
if (a) tail->next = a;
if (b) tail->next = b;
return head;
}
// merge sort
ListNode *sortList(ListNode *head) {
if (head == NULL || head->next == NULL) return head; // 防止只有一个节点时死循环
ListNode *mid = middleNode(head);
ListNode *first = head;
ListNode *second = mid->next;
mid->next = NULL;
first = sortList(first);
second = sortList(second);
return merge(first, second);
}