148.Sort List

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

归并排序

/**
 * 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;
        //mergesort,find the middle of the list

        ListNode *fast = head, *slow = head;

        while(fast->next && fast->next->next){
            fast = fast->next->next;
            slow = slow->next;
        }

        ListNode *split = slow->next;
        slow->next = nullptr;

        ListNode *l1 = sortList(head);
        ListNode *l2 = sortList(split);
        ListNode *newHead = merge(l1, l2);
        return newHead;
    }
private:
    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;
        }
    }
};

results matching ""

    No results matching ""