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;
    }
};
相关推荐
浅念-16 小时前
LeetCode 回溯算法题——综合练习
数据结构·c++·算法·leetcode·职场和发展·深度优先·dfs
圣保罗的大教堂17 小时前
leetcode 61. 旋转链表 中等
leetcode
珊瑚里的鱼20 小时前
leetcode42雨水
算法·leetcode
过期动态21 小时前
【LeetCode 热题 100】字母异位分组
java·算法·leetcode·职场和发展·哈希算法
alphaTao1 天前
LeetCode 每日一题 2026/5/18-2026/5/24
python·leetcode
过期动态1 天前
【LeetCode 热题 100】两数之和— 暴力法与哈希表法详解
java·数据结构·算法·leetcode·散列表
sheeta19981 天前
LeetCode 每日一题笔记 日期:2026.05.24 题目:1340. 跳跃游戏 V
笔记·leetcode·游戏
z200509301 天前
今日算法(组合问题III)(回溯的使用)
java·算法·leetcode
_深海凉_1 天前
LeetCode热题100-排序链表
算法·leetcode·链表
sheeta19981 天前
LeetCode 每日一题笔记 日期:2026.05.22 题目:33. 搜索旋转排序数组
笔记·算法·leetcode