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

猜你喜欢

转载自www.cnblogs.com/one-think/p/12674383.html