【力扣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);
    }
};
相关推荐
m0_706653234 小时前
基于C++的爬虫框架
开发语言·c++·算法
diediedei4 小时前
嵌入式数据库C++集成
开发语言·c++·算法
君义_noip4 小时前
洛谷 P3388 【模板】割点(割顶)
c++·算法·图论·信息学奥赛·csp-s
xie0510_4 小时前
string模拟实现
开发语言·c++·算法
xuedingbue4 小时前
数据结构与顺序表:高效数据管理秘籍
数据结构·算法·链表
星火开发设计4 小时前
共用体 union:节省内存的特殊数据类型
java·开发语言·数据库·c++·算法·内存
求梦8205 小时前
【力扣hot100题】合并两个有序链表(22)
算法·leetcode·链表
dcmfxvr5 小时前
adwawd
算法
踩坑记录5 小时前
leetcode hot100 21.合并两个有序链表 链表 easy
leetcode
啊阿狸不会拉杆5 小时前
《数字信号处理 》第 7 章-无限长单位冲激响应 (IIR) 数字滤波器设计方法
数据结构·算法·信号处理·数字信号处理·dsp