题解 | #单链表的排序#
单链表的排序
https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
struct ListNode* merge(struct ListNode* l1, struct ListNode* l2) {
struct ListNode dummy;
struct ListNode* tail = &dummy;
dummy.next = NULL;
while (l1 && l2) {
if (l1->val < l2->val) {
tail->next = l1;
l1 = l1->next;
} else {
tail->next = l2;
l2 = l2->next;
}
tail = tail->next;
}
tail->next = l1 ? l1 : l2;
return dummy.next;
}
struct ListNode* split(struct ListNode* head) {
if (!head || !head->next) return head;
struct ListNode dummy;
struct ListNode* slow = &dummy, *fast = head;
dummy.next = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
struct ListNode* second = slow->next;
slow->next = NULL;
return second;
}
struct ListNode* sortInList(struct ListNode* head) {
if (!head || !head->next) return head;
struct ListNode* second = split(head);
head = sortInList(head);
second = sortInList(second);
return merge(head, second);
}
