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;
    }
};
相关推荐
Alfred king8 小时前
面试150 LRU缓存
链表·缓存·哈希表·lru·双向链表
愚润求学8 小时前
【动态规划】01背包问题
c++·算法·leetcode·动态规划
dying_man11 小时前
LeetCode--44.通配符匹配
算法·leetcode
Paper Clouds11 小时前
代码随想录|图论|15并查集理论基础
数据结构·算法·leetcode·深度优先·图论
GGBondlctrl13 小时前
【leetcode】字符串,链表的进位加法与乘法
算法·leetcode·链表·字符串相加·链表相加·字符串相乘
打野二师兄14 小时前
LeetCode经典题解:21、合并两个有序链表
算法·leetcode·链表
前端拿破轮14 小时前
腾讯面试官:听说你在字节面试用栈实现队列,那怎么用队列实现栈呢?
算法·leetcode·面试
Y1nhl1 天前
力扣_二叉树的BFS_python版本
python·算法·leetcode·职场和发展·宽度优先
Owen_Q1 天前
Leetcode百题斩-二分搜索
算法·leetcode·职场和发展
zstar-_1 天前
Claude code在Windows上的配置流程
笔记·算法·leetcode