Skip to content

Commit 55bcf55

Browse files
committed
"Sort List"
1 parent d651dd3 commit 55bcf55

File tree

2 files changed

+96
-1
lines changed

2 files changed

+96
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ The `☢` means that you need to have a LeetCode Premium Subscription.
140140
| 151 | [Reverse Words in a String] | [C](src/151.c) |
141141
| 150 | [Evaluate Reverse Polish Notation] | [C](src/150.c) |
142142
| 149 | [Max Points on a Line] | |
143-
| 148 | [Sort List] | |
143+
| 148 | [Sort List] | [C](src/148.c) |
144144
| 147 | [Insertion Sort List] | |
145145
| 146 | [LRU Cache] | [C](src/146.c) |
146146
| 145 | [Binary Tree Postorder Traversal] | [C](src/145.c) |

src/148.c

+95
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
struct ListNode {
5+
int val;
6+
struct ListNode *next;
7+
};
8+
9+
struct ListNode* merge(struct ListNode *left, struct ListNode *right) {
10+
if (left == NULL) return right;
11+
if (right == NULL) return left;
12+
13+
struct ListNode *ans = NULL;
14+
struct ListNode **p = &ans;
15+
16+
while (left && right) {
17+
if (left->val <= right->val) {
18+
*p = left;
19+
p = &((*p)->next);
20+
left = left->next;
21+
}
22+
else {
23+
*p = right;
24+
p = &((*p)->next);
25+
right = right->next;
26+
}
27+
}
28+
29+
if (left) {
30+
*p = left;
31+
}
32+
else if (right) {
33+
*p = right;
34+
}
35+
36+
return ans;
37+
}
38+
39+
struct ListNode* sortList(struct ListNode* head) {
40+
if (head == NULL) return NULL;
41+
if (head->next == NULL) return head;
42+
43+
struct ListNode *p = head;
44+
int len = 0;
45+
while (p) {
46+
len++;
47+
p = p->next;
48+
}
49+
50+
struct ListNode *mid = head;
51+
struct ListNode *prev = NULL;
52+
int i = len / 2;
53+
while (i--) {
54+
prev = mid;
55+
mid = mid->next;
56+
}
57+
prev->next = NULL;
58+
59+
struct ListNode *left = sortList(head);
60+
struct ListNode *right = sortList(mid);
61+
62+
return merge(left, right);
63+
}
64+
65+
int main() {
66+
struct ListNode *head = (struct ListNode *)calloc(5, sizeof(struct ListNode));
67+
struct ListNode **p = &head;
68+
int i;
69+
for (i = 0; i < 5; i++) {
70+
(*p)->val = 5 - i;
71+
(*p)->next = *p + 1;
72+
p = &((*p)->next);
73+
}
74+
*p = NULL;
75+
76+
printf("List: ");
77+
struct ListNode *q = head;
78+
while (q != NULL) {
79+
printf("%d->", q->val);
80+
q = q->next;
81+
}
82+
printf("N\n");
83+
84+
struct ListNode *ret = sortList(head);
85+
86+
printf("Sort result: ");
87+
q = ret;
88+
while (q != NULL) {
89+
printf("%d->", q->val);
90+
q = q->next;
91+
}
92+
printf("N\n");
93+
94+
return 0;
95+
}

0 commit comments

Comments
 (0)