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;
        }
    }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM