-
Notifications
You must be signed in to change notification settings - Fork 0
/
SortList.cpp
93 lines (76 loc) · 1.81 KB
/
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
int len(ListNode* A){
if(A==NULL)return 0;
return 1+len(A->next);
}
pair<ListNode*,ListNode*> partition(ListNode* head) {
ListNode* n1=NULL,*n2=NULL,*it=NULL,*jt=NULL;
int n = len(head);
ListNode* i=head;
for(int j=1;j<n/2;j++){
i=i->next;
}
auto tmp = i->next;
i->next=NULL;
return make_pair(head,tmp);
}
ListNode* merge(ListNode* a,ListNode* b) {
if(a==NULL)return b;
if(b==NULL)return a;
auto it=a,jt=b;
ListNode * res=NULL,*i;
while(it!=NULL and jt!=NULL){
if(it->val<=jt->val){
if(res==NULL){
res=i=it;
}else{
i->next=it;
i=i->next;
}
it=it->next;
}
else{
if(res==NULL){
res=i=jt;
}else{
i->next=jt;
i=i->next;
}
jt=jt->next;
}
}
while(it!=NULL ){
i->next=it;
i=i->next;
it=it->next;
}
while(jt!=NULL ){
i->next=jt;
i=i->next;
jt=jt->next;
}
return res;
}
ListNode* my_sort(ListNode* head) {
// if(head==NULL)return head;
int n = len(head);
if(n<=1)return head;
// int x= min(head->val,head->next->val);
auto p=partition(head);
auto left = my_sort(p.first);
auto right = my_sort(p.second);
return merge(left,right);
}
class Solution {
public:
ListNode* sortList(ListNode* head) {
return my_sort(head);
}
};