题解 | #单链表的排序#

单链表的排序

https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
#include <cerrno>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 the head node
     * @return ListNode类
     */
    ListNode* sortInList(ListNode* head) {
        if(head->next==nullptr)
            return head;

        return MergeSortList(head);
    }
    ListNode* MergeSortList(ListNode* head)
    {
        if(head==nullptr||head->next==nullptr)
            return head;

        ListNode* fast=head->next;
        ListNode* slow=head;

        while(fast!=nullptr&&fast->next!=nullptr)
        {
            fast=fast->next->next;
            slow=slow->next;
        }

        ListNode* mid=slow->next;
        slow->next=nullptr;

        ListNode* Left=MergeSortList(head);
        ListNode* Right=MergeSortList(mid);

        return Merge(Left,Right);
    }
    ListNode* Merge(ListNode* Left,ListNode* Right)
    {
        ListNode* p=new ListNode(-1);
        ListNode* ptr=p;

        while(Left!=nullptr&&Right!=nullptr)
        {
            if(Left->val<Right->val)
            {
                ptr->next=Left;
                ptr=ptr->next;
                Left=Left->next;
            }
            else
            {
                ptr->next=Right;
                ptr=ptr->next;
                Right=Right->next;
            }
        }
        if(Left!=nullptr)
            ptr->next=Left;
        else
            ptr->next=Right;
        return p->next;
    }
};

全部评论

相关推荐

2025-12-28 16:32
重庆邮电大学 Java
程序员花海:1.技能放最后,来面试默认你都会,技能没啥用 2.实习写的看起来没啥含金量,多读读部门文档,包装下 接LLM这个没含金量 也不要用重构这种 不会给实习生做的 3.抽奖这个还是Demo项目,实际在公司里面要考虑策略,满减,触发点,触发规则 库存 之类的,不是这个项目这么简单 4.教育背景提前,格式为 教育背景 实习 项目 技能 自我评价
简历被挂麻了,求建议
点赞 评论 收藏
分享
2025-11-24 11:23
门头沟学院 软件测试
Jcwemz:都快过年了,就没几家真正招的,100个投递两个面试算是正常的了 加上你的简历,其实你不能很好的描述你自己是做什么的 两个月的时间,你就负责到自动化的内容啦?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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