天天看點

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(n log n) 時間複雜度和常數級空間複雜度下,對連結清單進行排序。

示例 1:

輸入: 4->2->1->3
輸出: 1->2->3->4
      
示例 2:
輸入: -1->5->3->4->0
輸出: -1->0->3->4->5      

思路:時間為nlogn, 是以必須想到快排,堆排序,歸并。那就想到用歸并對連結清單 排序,147題用插入對連結清單排序時間為n^2.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if(!head || !head->next) return head;
        ListNode *cur=head,*slow=head,*quick=head;
        while(quick && quick->next)
        {
            cur=slow;
            slow=slow->next;
            quick=quick->next->next;
        }
        cur->next=NULL;
        return merge(sortList(head),sortList(slow));
    }
    // ListNode* merge(ListNode* l1,ListNode* l2)   //非遞歸版本
    // {
    //     ListNode * newhead = new ListNode(-1);
    //     ListNode * newnode = newhead;
    //     while(l1 && l2)
    //     {
    //         if(l1->val < l2->val)
    //         {
    //             newnode->next=l1;
    //             l1=l1->next;
    //         }else{
    //             newnode->next=l2;
    //             l2=l2->next;
    //         }
    //         newnode=newnode->next;
    //     }
    //     if(l1) newnode->next=l1;
    //     if(l2) newnode->next=l2;
    //     return newhead->next;
    // }
    ListNode * merge(ListNode* l1,ListNode * l2)   //遞歸版本
    {
        if(!l1) return l2;
        if(!l2) return l1;
        if(l1->val <l2->val)
        {
            l1->next = merge(l1->next,l2);
            return l1;
        }else{
            l2->next = merge(l1,l2->next);
            return l2;
        }
    }
};