-
Notifications
You must be signed in to change notification settings - Fork 0
/
sort-list.cpp
149 lines (138 loc) · 3.12 KB
/
sort-list.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
void printLink(ListNode*head){
while(head){
cout<<head->val<<"->";
head = head->next;
}
cout<<endl;
}
class Solution {
public:
ListNode *sortList(ListNode *head) {
int length = 0;
ListNode *p=head;
while(p){
p = p->next;
length++;
}
cout<<"length:"<<length<<endl;
if(length<2)
return head;
if(length==2){
if(head->val<=head->next->val)
return head;
else{
ListNode *t=head->next;
head->next=NULL;
t->next=head;
return t;
}
}
int cnt=0;
p=head;
while(cnt<length/2){
p=p->next;
cnt++;
}
ListNode *first = head;
ListNode *second = p->next;
p->next = NULL;
printLink(first);
printLink(second);
first=sortList(first);
second=sortList(second);
printLink(first);
printLink(second);
return mergeSortedList1(first,second);
}
/*递归版本*/
ListNode *mergeSortedList(ListNode *first,ListNode *second){
cout<<"merge"<<endl;
printLink(first);
printLink(second);
if(first == NULL && second == NULL)
return NULL;
if(first == NULL)
return second;
if(second == NULL)
return first;
if(first->val < second->val){
first->next = mergeSortedList(first->next, second);
return first;
}else{
second->next = mergeSortedList(first, second->next);
return second;
}
}
/*O(n)版本*/
ListNode *mergeSortedList1(ListNode *first,ListNode*second){
ListNode *cur ,*head;
cur = NULL;
head = NULL;
while(first!=NULL&&second!=NULL){
if(first->val < second->val){
if(cur==NULL){
head = first;
cur = first;
}else{
cur->next = first;
cur = cur->next;
}
first = first->next;
}else{
if(cur==NULL){
head = second;
cur = second;
}else{
cur->next = second;
cur = cur->next;
}
second = second->next;
}
}
if(first==NULL&&second==NULL){
if(cur == NULL){
head = first;
}else{
cur->next = NULL;
}
}else if(first == NULL){
if(cur == NULL)
head = second;
else
cur->next = second;
}else if(second == NULL){
if(cur == NULL)
head = first;
else
cur->next = first;
}
return head;
}
};
int main(){
Solution s;
ListNode *head = new ListNode(7);
ListNode *p=head;
head->next = new ListNode(6);
head = head->next;
head->next = new ListNode(5);
head = head->next;
head->next = new ListNode(4);
head = head->next;
head->next = new ListNode(5);
head = head->next;
head->next = new ListNode(6);
head = head->next;
head->next = new ListNode(7);
printLink(p);
p = s.sortList(p);
printLink(p);
return 0;
}