zoukankan      html  css  js  c++  java
  • 148. 排序链表(c++)

    在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。

    示例 1:

    输入: 4->2->1->3
    输出: 1->2->3->4
    public:
        ListNode* sortList(ListNode* head) {
            return mergeSort(head);
        }
        ListNode* mergeSort(ListNode* node){
            if(!node || !node->next) return node;
            ListNode* fast = node;
            ListNode* slow = node;
            ListNode* breakN = node;
            while(fast && fast->next){
                fast = fast->next->next;
                breakN = slow;
                slow =slow->next;
            }
            breakN->next= nullptr;
            ListNode *l1 = mergeSort(node);
            ListNode *l2 = mergeSort(slow);
            return merge(l1,l2);
        }
        ListNode* merge(ListNode* l1,ListNode* l2){
            if(l1 == nullptr) return l2;
            if(l2 ==nullptr) return l1;
            if(l1->val <= l2->val){
                l1->next = merge(l1->next,l2);
                return l1;
            }else{
                l2->next = merge(l2->next,l1);
                return l2;
            }
        }
  • 相关阅读:
    麦肯锡矩阵导航图
    以业务为核心的云原生体系建设
    万字长文拿下HTTP
    人人都该懂的埋点知识
    淘宝的技术架构
    五步,快速理解一个行业
    一文读懂用户分层
    python13day
    python12day
    python11day
  • 原文地址:https://www.cnblogs.com/one-think/p/12674383.html
Copyright © 2011-2022 走看看