首页 > 代码库 > 148. Sort List

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