148. Sort List(链表的归并排序,用快慢指针来partition)

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) {}
 * };
 */
AC代码:

class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if(!head||!head->next)
            return head;
        ListNode* slow=head;
        ListNode* fast=head->next;
        while(fast&&fast->next){
            slow=slow->next;
            fast=fast->next->next;
        }
        //将链表分成两段
        //通过快慢指针,最后链表会被划分为许多只有1个或者2个节点的小段
        //然后再merge它们
        fast=slow->next;
        slow->next=NULL;
        return merge(sortList(head),sortList(fast));
    }
    
    ListNode* merge(ListNode* l1,ListNode* l2){
        ListNode dummy(0);
        ListNode* helper=&dummy;
        //画个图就明白了=。=
        while(l1&&l2){
            if(l1->valval){
                helper->next=l1;
                l1=l1->next;
            }
            else{
                helper->next=l2;
                l2=l2->next;
            }
            helper=helper->next;
        }
        if(l1)
            helper->next=l1;
        else
            helper->next=l2;
        return dummy.next;
    }
};




你可能感兴趣的:(LeetCode)