148. Sort List

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

class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if(head==NULL||head->next==NULL)
          return head;
        ListNode* slow = head;
        ListNode* fast = head;
        while(fast->next!=NULL&&fast->next->next!=NULL)
        {
            slow = slow->next;
            fast = fast->next->next;
        }
        ListNode* list = slow->next;
        slow->next = NULL;
        head = sortList(head);
        list = sortList(list);
        return merge(head,list);
    }
    
    ListNode* merge(ListNode* &list1,ListNode* &list2)
    {
        if(list1==NULL)
          return list2;
        if(list2==NULL)
          return list1;
        ListNode* newhead = new ListNode(-1);
        ListNode* last = newhead;
        while(list1!=NULL&&list2!=NULL)
        {
            if(list1->valval)
            {
                last->next = list1;
                last = last->next;
                list1 = list1->next; 
            }
            else
            {
                last->next = list2;
                last = last->next;
                list2 = list2->next;
            }
            
        }
        if(list1!=NULL)
            last->next = list1;
        else if(list2!=NULL)
            last->next = list2;
        return newhead->next;
    }
    
};

你可能感兴趣的:(148. Sort List)