leetcode 148. Sort List

148. Sort List

题目描述

代码:

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if(head == nullptr)
            return nullptr;
        return merge_sort(head,nullptr);
    }

    pair<ListNode*,ListNode*> find(ListNode* head){
        ListNode* fast = head;
        ListNode* slow = head;
        ListNode* preslow = nullptr;
        while(fast&&fast->next){
            fast = fast->next->next;
            preslow = slow;
            slow = slow->next;
        }
        if(preslow == nullptr)
            return {slow,slow};
        return {preslow,slow};
    }

    ListNode* merge_sort(ListNode *head,ListNode* tail){
        if(head == tail)
            return head;
        auto mid_pair = find(head);
        if(mid_pair.first == mid_pair.second)
            return head;
        mid_pair.first->next = nullptr;
        ListNode* left  = merge_sort(head,mid_pair.first);
        ListNode* right = merge_sort(mid_pair.second,tail);

        ListNode* dummy = new ListNode(-1,nullptr);
        ListNode* pre = dummy;
        while(left&&right){
            if(left->val < right->val){
                pre->next = left;
                pre = left;
                left = left->next;
            }else{
                pre->next = right;
                pre = right;
                right = right->next;
            }
        }
        if(left)
            pre->next = left;
        else
            pre->next = right;
        ListNode* newHead = dummy->next;
        delete dummy;
        return newHead;
    }
};
相关推荐
Owen_Q2 小时前
Leetcode百题斩-回溯
算法·leetcode·职场和发展
黎明smaly4 小时前
【数据结构与算法】LeetCode 每日三题
算法·leetcode·职场和发展
一只鱼^_4 小时前
力扣第450场周赛
数据结构·c++·算法·leetcode·近邻算法·广度优先·图搜索算法
小羊在奋斗5 小时前
【LeetCode 热题 100】有效的括号 / 最小栈 / 字符串解码 / 柱状图中最大的矩形
算法·leetcode·职场和发展
编程绿豆侠5 小时前
力扣HOT100之二叉树:124. 二叉树中的最大路径和
算法·leetcode·深度优先
蒟蒻小袁5 小时前
力扣面试150题-- 从中序与后序遍历序列构造二叉树
算法·leetcode·面试
Tisfy6 小时前
LeetCode 3356.零数组变换 II:二分查找 + I的差分数组
算法·leetcode·二分查找·题解·差分数组
asom226 小时前
LeetCode Hot100 (哈希)
算法·leetcode
SylviaW087 小时前
python-leetcode 67.寻找两个正序数组中的中位数
开发语言·python·leetcode