题解 | #单链表的排序#

单链表的排序

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

/**
 * struct ListNode {
 *  int val;
 *  struct ListNode *next;
 *  ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param head ListNode类 the head node
     * @return ListNode类
     */
    ListNode* mergeSort(ListNode* left, ListNode* right) {
        if (left == right) return left; //当只有一个点的时候,直接返回
        auto mid = left;
        auto fast = mid;
        while (fast->next != right && fast != right) {
            fast = fast->next->next;
            mid = mid->next;
        }//使用快慢指针将链表一分为二
        auto rhead = mergeSort(mid->next, right);//先对右边进行排序
        mid->next = nullptr;//切割左右链表
        auto lhead = mergeSort(left, mid);//然后对左边排序
        return merge(lhead, rhead);//假设左右两边是已经排列好的序列,合并左右两边的序列
    }
    ListNode* merge(ListNode* lhead, ListNode* rhead) {//合并两个链表
        auto dummy = new ListNode(-1);
        dummy->next = (lhead->val < rhead->val) ? lhead : rhead;
        auto pre = dummy;
        while (lhead != nullptr && rhead != nullptr) {
            if (lhead->val < rhead->val) {
                pre->next = lhead;
                lhead = lhead->next;
            } else {
                pre->next = rhead;
                rhead = rhead->next;
            }
            pre = pre->next;
        }
        if (lhead != nullptr) pre->next = lhead;
        if (rhead != nullptr) pre->next = rhead;
        return dummy->next;
    }
    ListNode* sortInList(ListNode* head) {
        // write code here
        auto p = head;
        while (p->next != nullptr) p = p->next; //找到链表的尾节点
        auto dummy = new ListNode(-1);
        dummy->next = mergeSort(head, p);//归并排序
        return dummy->next;
    }
};

全部评论

相关推荐

05-19 19:57
蚌埠学院 Python
2237:Gpa70不算高,建议只写排名,个人技能不在多而在精,缩到8条以内。项目留一个含金量高的,减少间距弄到一页,硕士简历也就一页,本科不要写很多
实习,投递多份简历没人回...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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