sort-list

作者: DaiMorph | 来源:发表于2019-06-25 01:36 被阅读0次
    class Solution {
    public:
        ListNode *sortList(ListNode *head) {
            if(!head||!head->next)return head;
            ListNode*slow=head,*fast=head->next;
            while(fast&&fast->next)//这里必须是fast=head->next,考虑偶数时slow的最终位置
            {
                slow=slow->next,fast=fast->next->next;
            }
            ListNode*l1=sortList(slow->next);
            slow->next=NULL;
            ListNode*l2=sortList(head);
            return mergelist(l1,l2);
        }
        ListNode*mergelist(ListNode*l1,ListNode*l2)
        {
            ListNode*dummy=new ListNode(-1);
            ListNode*root=dummy;
            while(l1&&l2)
            {
                if(l1->val<l2->val)root->next=l1,l1=l1->next,root=root->next;
                else root->next=l2,l2=l2->next,root=root->next;
            }
            if(l1)root->next=l1;
            if(l2)root->next=l2;
            return dummy->next;
        }
    };
    

    相关文章

      网友评论

          本文标题:sort-list

          本文链接:https://www.haomeiwen.com/subject/tykzqctx.html