【力扣hot100题】(032)排序链表

挺难的,主要是对排序算法不熟悉。

看了答案,归并排序真的是一个很好的解法。

大致思路是递归,将链表不断拆分为小块,每块进行排序后合并新块。

这种排序对链表来说真的是个很不错的选择,因为链表二分可以用快慢指针,合并之前做过,很好做。

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* dg(ListNode* head,ListNode* tail){
        if(head==nullptr) return head;
        if(head->next==tail){
            head->next=nullptr;
            return head;
        }
        ListNode* slow=head;
        ListNode* fast=head;
        while(fast!=tail){
            slow=slow->next;
            fast=fast->next;
            if(fast!=tail) fast=fast->next;
        }
        ListNode* h=dg(head,slow);
        ListNode* t=dg(slow,tail);
        ListNode* pre=new ListNode(0);
        ListNode* result=pre;
        while(h||t){
            if(t==nullptr||h&&h->val<t->val){
                pre->next=h;
                h=h->next;
            }
            else if(h==nullptr||h->val>=t->val){
                pre->next=t;
                t=t->next;
            }
            pre=pre->next;
        }
        return result->next;
    }
    ListNode* sortList(ListNode* head) {
        return dg(head,nullptr);
    }
};
相关推荐
地平线开发者15 小时前
profiler debug 工具用法与高一致性策略
算法·自动驾驶
编程大师哥15 小时前
匿名函数 lambda + 高阶函数
java·python·算法
我叫袁小陌16 小时前
算法解题思路指南
算法
地平线开发者16 小时前
Conv+BN+Add+ReLU 融合机制简介
算法·自动驾驶
yuanyuan2o216 小时前
模型预训练:Hugging Face Transformers 基础
算法·ai·语言模型·自然语言处理·nlp·深度优先
杨充16 小时前
1.3 浮点型数据设计灵魂
开发语言·python·算法
妄想出头的工业炼药师16 小时前
GS slam mono
算法·开源
_日拱一卒17 小时前
LeetCode:207课程表
java·数据结构·算法·leetcode·职场和发展
用户9874092388719 小时前
llamafactory 0.6.3 没有 llamafactory-cli
算法