题解 | #单链表的排序#

单链表的排序

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);
}

全部评论

相关推荐

10-05 23:02
东北大学 Java
我说句实话啊:那时候看三个月培训班视频,随便做个项目背点八股,都能说3 40w是侮辱价
点赞 评论 收藏
分享
挣K存W养DOG:他真的很中意你,为什么不回他
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务