排序链表(归并排序)

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);
    }
};
相关推荐
mmmmath_31 小时前
LeetCode.104.二叉树的最大深度
数据结构·leetcode
信奥卷王8 小时前
[GESP202509 六级] 划分字符串(含视频)
数据结构·算法
m0_752035638 小时前
Redis 数据结构总结
数据结构·数据库·redis
tachibana28 小时前
Go 语言的 Map 是否是并发安全的?
开发语言·数据结构·后端·golang·go·语言
Logic1019 小时前
C语言/数据结构字符串题解:统计“chhc“子串权值总和——一次遍历模式匹配
c语言·数据结构·算法·字符串·时间复杂度·空间复杂度·ascii
我命由我123459 小时前
LRU 缓存淘汰策略
数据结构·redis·学习·mysql·算法·缓存·学习方法
垆边人似月.10 小时前
华为题:合并区间
数据结构·c++·算法
垆边人似月.10 小时前
华为题:滑动窗口最大值
数据结构·c++·算法
m0_5474866610 小时前
《数据结构 (C语言)》期末试卷及答案(10套)2026版
c语言·开发语言·数据结构
杜 硕11 小时前
归并排序详解
数据结构·算法·排序算法