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;
    }
};
相关推荐
未知陨落3 小时前
LeetCode:95.编辑距离
算法·leetcode
名誉寒冰6 小时前
【LeetCode】454. 四数相加 II 【分组+哈希表】详解
算法·leetcode·散列表
tao3556677 小时前
【Python刷力扣hot100】49. Group Anagrams
开发语言·python·leetcode
夏鹏今天学习了吗8 小时前
【LeetCode热题100(35/100)】LRU 缓存
算法·leetcode·缓存
zh_xuan9 小时前
LeeCode92. 反转链表II
数据结构·算法·链表·leecode
2401_8414956410 小时前
【数据结构】汉诺塔问题
java·数据结构·c++·python·算法·递归·
Q741_14710 小时前
C++ 位运算 高频面试考点 力扣137. 只出现一次的数字 II 题解 每日一题
c++·算法·leetcode·面试·位运算
墨染点香11 小时前
LeetCode 刷题【103. 二叉树的锯齿形层序遍历、104. 二叉树的最大深度、105. 从前序与中序遍历序列构造二叉树】
算法·leetcode·职场和发展
Brookty12 小时前
【算法】二分查找(一)朴素二分
java·学习·算法·leetcode·二分查找