LeetCode-148-Sort List

Posted 无名路人甲

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-148-Sort List相关的知识,希望对你有一定的参考价值。

算法描述:

Sort a linked list in O(n log n) time using constant space complexity.

Example 1:

Input: 4->2->1->3
Output: 1->2->3->4

Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5

解题思路:时间复杂度O(nlogn)。写了快排感觉很奇怪,看了其他人答案,发现都是归并排序。

快排代码很乱,如下。

    ListNode* sortList(ListNode* head) {
        if(head==nullptr || head->next==nullptr) return head;
        ListNode* leftHead = new ListNode(INT_MIN);
        ListNode* rightHead = new ListNode(INT_MIN);
        ListNode* lc = leftHead;
        ListNode* rc = rightHead;
        
        ListNode* pivot = head;
        ListNode* cur = head->next;
        while(cur!=nullptr){
            if(cur->val < pivot->val){
                lc->next = cur;
                lc = lc->next;
            }else {
                rc->next = cur;
                rc = rc->next;
            }
            cur=cur->next;
        }
        lc->next = nullptr;
        rc->next = nullptr;
        
        leftHead->next = sortList(leftHead->next);
        rightHead->next = sortList(rightHead->next);
        cur = leftHead;
        while(cur->next!=nullptr) cur=cur->next;
        cur->next=pivot;
        cur->next->next = rightHead->next;
        return leftHead->next;
    }

归并排序代码:

 ListNode* sortList(ListNode* head) {
        if(head==nullptr || head->next==nullptr) return head;
        ListNode* fast = head->next;
        ListNode* slow = head;
        while(fast!=nullptr && fast->next!=nullptr){
            fast=fast->next->next;
            slow=slow->next;
        }
        
        fast = slow->next;
        slow->next = nullptr;
     
        return merge(sortList(fast), sortList(head));
    }
    ListNode* merge(ListNode* l1, ListNode* l2){
        
        ListNode* dup = new ListNode(-1);
        ListNode* cur = dup;
        while(l1!=nullptr && l2!=nullptr){
            if(l1->val < l2->val){
                cur->next=l1;
                l1=l1->next;
            }else{
                cur->next=l2;
                l2=l2->next;
            }
            cur=cur->next;
        }
        
        if(l1!=nullptr) cur->next = l1;
        else cur->next = l2;
        return dup->next;
    }

 

以上是关于LeetCode-148-Sort List的主要内容,如果未能解决你的问题,请参考以下文章

[Lintcode]98. Sort List/[Leetcode]148. Sort List

#Leetcode# 148. Sort List

leetcode148. Sort List

Leetcode148-Sort_List

leetcode148. Sort List

LeetCode-148-Sort List