题解 | #单链表的排序#

单链表的排序

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

全部评论

相关推荐

StephenZ_:我9月份找的第一段实习也是遇到这种骗子公司了,问他后端有多少人和我说7个正职,进去一看只有一个后端剩下的都是产品前端算法(没错甚至还有算法)。还是某制造业中大厂,我离职的时候还阴阳怪气我
点赞 评论 收藏
分享
八极星:有什么不能问的,(/_\),这又不是多珍贵的机会,你有什么可失去的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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