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;
    }
};
相关推荐
夏幻灵6 小时前
LeetCode 21:合并两个有序链表——双指针与哑节点详解
算法·leetcode·链表
Navigator_Z8 小时前
LeetCode //C - 1286. Iterator for Combination
c语言·算法·leetcode
圣保罗的大教堂9 小时前
leetcode 301. 删除无效的括号 困难
leetcode
夏幻灵11 小时前
每日一题:LeetCode 206:反转链表——三指针与原地反转详解
算法·leetcode·链表
Tisfy15 小时前
LeetCode 0301.删除无效的括号:二进制枚举 / 回溯
算法·leetcode·字符串·题解·回溯·括号匹配·二进制枚举
Nil20815 小时前
leetcode 322零钱兑换
算法·leetcode·职场和发展
yi01115 小时前
DAY24: LeetCode 167:两数之和 II|从暴力枚举到左右双指针
笔记·python·算法·leetcode·二分查找·双指针
木井巳15 小时前
【BFS 解决拓扑排序】课程表
java·算法·leetcode·广度优先·宽度优先·推荐算法·图搜索算法
yi01115 小时前
LeetCode 15:三数之和|排序 + 双指针,如何避免重复答案?
笔记·python·算法·leetcode·双指针
alphaTao16 小时前
LeetCode 每日一题 2026/10/5-2026/10/11
算法·leetcode