排序链表(归并排序)

148. 排序链表 - 力扣(LeetCode)

以O(nlogn)时间复杂度, O(1)空间复杂度 排序链表

涉及知识点:

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 {
private:
    // 合并有序链表
    ListNode *mergeList(ListNode *list1, ListNode *list2){
        ListNode *dummyhead = new ListNode(0);
        ListNode *cur = dummyhead;
        while(list1 && list2){
            if(list1->val <= list2->val){
                cur->next = list1;
                list1 = list1->next;
            }else{
                cur->next = list2;
                list2 = list2->next;
            }
            cur = cur->next;
        }
        cur->next = list1 ? list1 : list2;
        return dummyhead->next;
    }
    // 找到链表的中间节点
    ListNode *findMid(ListNode *head, ListNode *end){
        ListNode *fast=head, *slow=head;
        while(fast!=end && fast->next!=end){
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow;
    }
    // 归并排序
    ListNode *mergeSort(ListNode *head, ListNode *end){
        // end_cond
        if(!head) return head;
        if(head->next == end){
            head->next = nullptr;
            return head;
        } 
        // find mid
        ListNode *mid = findMid(head, end);
        // group
        ListNode *list_l = mergeSort(head, mid);
        ListNode *list_r = mergeSort(mid, end);
        // merge
        return mergeList(list_l, list_r);
    }
public:
    // 以O(nlogn)时间复杂度, O(1)空间复杂度 排序链表
    ListNode *sortList(ListNode *head) {
        return mergeSort(head, nullptr);
    }
};
相关推荐
m0_547486662 天前
《数据结构教程》全套 PPT课件2026
数据结构
tryxr2 天前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_32 天前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
All for pursuit.2 天前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
All for pursuit.2 天前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
渡我白衣2 天前
HttpRequest与HttpResponse的实现
服务器·数据结构·c++·人工智能·tcp/ip·机器学习·caffe
晴天的雨.9922 天前
【C++算法】和为s的两个数
开发语言·数据结构·c++·算法
无敌贵点大王2 天前
RTThread学习记录11——RT-Thread 设备模型吃透:UART/ADC/PWM/PIN 到底有什么区别?
c语言·stm32·学习·链表
淡海水2 天前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
Logic1012 天前
C语言/数据结构位运算题解:异或XOR找出时尚聚会中的“独特颜色“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质