-
Notifications
You must be signed in to change notification settings - Fork 319
/
Copy path148_SortList.cpp
102 lines (94 loc) · 2.55 KB
/
148_SortList.cpp
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*
* @Author: [email protected]
* @Last Modified time: 2016-09-06 20:40:19
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode * merge_list(ListNode *left, ListNode *right){
ListNode *pre_head = new ListNode(0);
ListNode *scan = pre_head;
while (left && right){
if (left->val <= right->val){
scan->next = left;
left = left->next;
}
else{
scan->next = right;
right = right->next;
}
scan = scan->next;
}
if(left != nullptr) scan->next = left;
if(right != nullptr) scan->next = right;
return pre_head->next;
}
ListNode* sortList(ListNode* head) {
if(head == nullptr || head->next == nullptr){
return head;
}
ListNode *slow=head, *fast=head, *pre_tail= nullptr;
// Cut the list into two parts
while (fast != nullptr and fast->next != nullptr){
pre_tail = slow;
slow = slow->next;
fast = fast->next->next;
}
pre_tail->next = nullptr;
ListNode *left = sortList(head);
ListNode *right = sortList(slow);
return merge_list(left, right);
}
};
// QuickSort. Time Limit Exceeded if using no trick.
// Refer to:
// https://discuss.leetcode.com/topic/15029/56ms-c-solutions-using-quicksort-with-explanations/2
class Solution_2 {
public:
ListNode* partition(ListNode *begin, ListNode *end){
if(begin == nullptr || begin->next == end){
return begin;
}
ListNode *scan = begin->next;
int pivot = begin->val;
ListNode *pos = begin;
while(scan != end){
if(scan->val <= pivot){
pos = pos->next;
if(pos != scan){
swap(pos->val, scan->val);
}
}
scan = scan->next;
}
swap(pos->val, begin->val);
return pos;
}
ListNode* quicksort(ListNode* begin, ListNode* end){
if(begin == end || begin->next == end){
return begin;
}
ListNode *pos = partition(begin, end);
ListNode* head = quicksort(begin, pos);
quicksort(pos->next, end);
return head;
}
ListNode* sortList(ListNode* head) {
return quicksort(head, nullptr);
}
};
/*
[]
[1]
[1,2]
[5,1,2]
[5,1,2,3]
[5,1,2,3,6,7,8,9,12,2]
*/