- Notifications
You must be signed in to change notification settings - Fork 117
/
Copy path148.c
95 lines (79 loc) · 1.83 KB
/
148.c
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
#include<stdio.h>
#include<stdlib.h>
structListNode {
intval;
structListNode*next;
};
structListNode*merge(structListNode*left, structListNode*right) {
if (left==NULL) returnright;
if (right==NULL) returnleft;
structListNode*ans=NULL;
structListNode**p=&ans;
while (left&&right) {
if (left->val <= right->val) {
*p=left;
p=&((*p)->next);
left=left->next;
}
else {
*p=right;
p=&((*p)->next);
right=right->next;
}
}
if (left) {
*p=left;
}
elseif (right) {
*p=right;
}
returnans;
}
structListNode*sortList(structListNode*head) {
if (head==NULL) returnNULL;
if (head->next==NULL) returnhead;
structListNode*p=head;
intlen=0;
while (p) {
len++;
p=p->next;
}
structListNode*mid=head;
structListNode*prev=NULL;
inti=len / 2;
while (i--) {
prev=mid;
mid=mid->next;
}
prev->next=NULL;
structListNode*left=sortList(head);
structListNode*right=sortList(mid);
returnmerge(left, right);
}
intmain() {
structListNode*head= (structListNode*)calloc(5, sizeof(structListNode));
structListNode**p=&head;
inti;
for (i=0; i<5; i++) {
(*p)->val=5-i;
(*p)->next=*p+1;
p=&((*p)->next);
}
*p=NULL;
printf("List: ");
structListNode*q=head;
while (q!=NULL) {
printf("%d->", q->val);
q=q->next;
}
printf("N\n");
structListNode*ret=sortList(head);
printf("Sort result: ");
q=ret;
while (q!=NULL) {
printf("%d->", q->val);
q=q->next;
}
printf("N\n");
return0;
}