-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkSort.cpp
More file actions
86 lines (71 loc) · 1.19 KB
/
linkSort.cpp
File metadata and controls
86 lines (71 loc) · 1.19 KB
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
#include <iostream>
struct Node{
int data;
Node *next;
};
typedef Node *List;
List merge(List l1, List l2){
if(!l1)
return l2;
else if (!l2)
return l1;
//both no null
List p = NULL;
if(l1->data < l2->data){
p = l1;
p->next = merge(p->next, l2);
}
else {
p = l2;
p->next = merge(l1, p->next);
}
return p;
}
void mergeSortList(List &l) {// sort n length list
if (!l || ! l->next)//0 or 1
return ;
List l1, l2;
List slow, fast;
l1 = l; //first segment
slow = l;
fast = l->next;
while(fast){
fast = fast->next;
if(fast){
fast = fast->next;
slow = slow->next;
}
}
l2 = slow->next;
slow->next = NULL;
mergeSortList(l1);
mergeSortList(l2);
l = merge(l1, l2);
}
using namespace std;
void pl(List l){
while(l ){
cout << l->data <<" ";
l=l->next;
}
cout << endl;
}
int main(void){
int d, i = 0;
List head,cur;
cur = head = new Node;
cur->next = NULL;
while(cin >> d){
cur->next = new Node;
cur= cur->next;
cur->next = NULL;
cur->data = d;
++i;
}
//input data
pl(head->next);
//sort
mergeSortList(head->next);
pl(head->next);
return 0;
}