排序链表(归并排序)

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);
    }
};
相关推荐
<但凡.24 分钟前
题海拾贝:P9241 [蓝桥杯 2023 省 B] 飞机降落
数据结构·算法·蓝桥杯
Spring小子29 分钟前
蓝桥杯[每日两题] 真题:好数 神奇闹钟 (java版)
java·数据结构·算法·蓝桥杯
记得早睡~1 小时前
leetcode654-最大二叉树
javascript·数据结构·算法·leetcode
写代码的橘子n1 小时前
unordered_set 的常用函数
数据结构·算法·哈希算法
*.✧屠苏隐遥(ノ◕ヮ◕)ノ*.✧2 小时前
C语言_数据结构总结6:链式栈
c语言·开发语言·数据结构·算法·链表·visualstudio·visual studio
于慨2 小时前
数据结构(王卓版)
数据结构
田梓燊2 小时前
leetcode 95.不同的二叉搜索树 Ⅱ
数据结构·算法·leetcode
情深不寿3173 小时前
数据结构--AVL树
数据结构·c++
孑么5 小时前
力扣 编辑距离
java·数据结构·算法·leetcode·职场和发展·贪心算法·动态规划
手握风云-5 小时前
Java数据结构第二十期:解构排序算法的艺术与科学(二)
数据结构·算法·排序算法