forked from lennylxx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
148.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>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* merge(struct ListNode *left, struct ListNode *right) {
if (left == NULL) return right;
if (right == NULL) return left;
struct ListNode *ans = NULL;
struct ListNode **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;
}
else if (right) {
*p = right;
}
return ans;
}
struct ListNode* sortList(struct ListNode* head) {
if (head == NULL) return NULL;
if (head->next == NULL) return head;
struct ListNode *p = head;
int len = 0;
while (p) {
len++;
p = p->next;
}
struct ListNode *mid = head;
struct ListNode *prev = NULL;
int i = len / 2;
while (i--) {
prev = mid;
mid = mid->next;
}
prev->next = NULL;
struct ListNode *left = sortList(head);
struct ListNode *right = sortList(mid);
return merge(left, right);
}
int main() {
struct ListNode *head = (struct ListNode *)calloc(5, sizeof(struct ListNode));
struct ListNode **p = &head;
int i;
for (i = 0; i < 5; i++) {
(*p)->val = 5 - i;
(*p)->next = *p + 1;
p = &((*p)->next);
}
*p = NULL;
printf("List: ");
struct ListNode *q = head;
while (q != NULL) {
printf("%d->", q->val);
q = q->next;
}
printf("N\n");
struct ListNode *ret = sortList(head);
printf("Sort result: ");
q = ret;
while (q != NULL) {
printf("%d->", q->val);
q = q->next;
}
printf("N\n");
return 0;
}