题解 | #单链表的排序#

单链表的排序

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

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-09 12:11
点赞 评论 收藏
分享
06-08 22:25
门头沟学院 Java
从零开始的转码生活:这hr不会打开手机不分青红皂白给所有人群发这句话,过一会再给所有人再发一遍,这肯定会有重复的,不管,再过一会再发一遍
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务