mirror of
https://github.com/arkorty/LeetCode.git
synced 2026-03-17 16:51:46 +00:00
Initial commit
This commit is contained in:
32
Medium/sort-list/solution.c
Normal file
32
Medium/sort-list/solution.c
Normal file
@@ -0,0 +1,32 @@
|
||||
struct ListNode *merge(struct ListNode *left, struct ListNode *right) {
|
||||
if (!left) {
|
||||
return right;
|
||||
}
|
||||
if (!right) {
|
||||
return left;
|
||||
}
|
||||
|
||||
if (left->val < right->val) {
|
||||
left->next = merge(left->next, right);
|
||||
return left;
|
||||
} else {
|
||||
right->next = merge(left, right->next);
|
||||
return right;
|
||||
}
|
||||
}
|
||||
|
||||
struct ListNode *sortList(struct ListNode *head) {
|
||||
if (!head || !head->next) {
|
||||
return head;
|
||||
}
|
||||
struct ListNode *fast, *midd, *bmid;
|
||||
fast = midd = head;
|
||||
while (fast && fast->next) {
|
||||
bmid = midd;
|
||||
fast = fast->next->next;
|
||||
midd = midd->next;
|
||||
}
|
||||
|
||||
bmid->next = NULL;
|
||||
return merge(sortList(head), sortList(midd));
|
||||
}
|
||||
Reference in New Issue
Block a user