148. Sort List

Posted 修修55

tags:

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

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

用mergeSort.快排的时间复杂度最差是n^2;

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *mergeList(ListNode *head1,ListNode *head2){
        if(!head1)return head2;
        if(!head2)return head1;
        
        ListNode * res = new ListNode(-1);
        ListNode * tmp = res;
        ListNode * p = head1;
        ListNode * q = head2;
        
        while(p && q){
            if(p->val<=q->val){
                tmp->next = p;
                tmp = p;
                p = p->next;
            }else{
                tmp->next = q;
                tmp = q;
                q = q->next;
            }
        }
        
        if(p) tmp->next = p;
        if(q) tmp->next = q;
        
        return res->next;
    }
    
    ListNode* sortList(ListNode* head) {
        if(!head || !head->next){
            return head;
        }

        ListNode *pSlow = head;
        ListNode *pFast = head;
        while(pFast->next && pFast->next->next){
            pFast = pFast->next->next;
            pSlow = pSlow->next;
        }
        
        ListNode *head2= pSlow->next;
        pSlow->next = NULL;
        ListNode *head1= head;
        
        head1 = sortList(head1);
        head2 = sortList(head2);
        return mergeList(head1,head2);
    }
};

 

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

148. Sort List

[LeetCode] 148. Sort List

148. Sort List

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

148. Sort List

148. Sort List