wfxr
10/26/2016 - 9:45 AM

链表排序算法

链表排序算法

class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if (!head || !head->next) return head;
        auto fast = head, slow = head;
        while (fast->next && fast->next->next) {
            slow = slow->next;
            fast = fast->next->next;
        }
        
        auto mid = slow->next;
        slow->next = nullptr;
        return merge(sortList(head), sortList(mid));
    }
    
    ListNode* merge(ListNode *l1, ListNode *l2) {
        auto sentinel = new ListNode(0);
        auto tail = sentinel;
        while (l1 && l2) {
            if (l2->val < l1->val) {
                tail->next = l2;
                l2 = l2->next;
            } else {
                tail->next = l1;
                l1 = l1->next;
            }
            tail = tail->next;
        }
        if (l1) tail->next = l1;
        if (l2) tail->next = l2;
        return sentinel->next;
    }
};