zoukankan      html  css  js  c++  java
  • 20.11.21 leetcode148 链表排序

    题目链接:https://leetcode-cn.com/problems/sort-list/

    题意:要求以O(nlogn)的复杂度给一个链表排序

    分析:昨天那道题的升级版,这里用的是归并排序的思想,自顶向下的排序,从一开始完整的链表不断的每次分成两段,分到每段只有一个结点为止,再一点点的合并,要注意的是sortlist的函数是前闭后开的。

    class Solution {
    public:
        ListNode* sortList(ListNode* head) {
            return sortList(head,nullptr);
        }
    
        ListNode* sortList(ListNode* head,ListNode* tail){
            //cout<<233<<endl;
            if(head==nullptr)return head;
            if(head->next==tail){
                head->next=nullptr;
                return head;
            }
            ListNode* slow=head,*fast=head;
            while(fast!=tail){
                slow=slow->next;
                fast=fast->next;
                if(fast!=tail)fast=fast->next;
            }
            return merge(sortList(head,slow),sortList(slow,tail));
        }
    
        ListNode* merge(ListNode* head1,ListNode* head2){
            ListNode* dummyHead=new ListNode(0);
            ListNode* tmp=dummyHead;
            ListNode* temp1=head1,*temp2=head2;
            while(temp1!=nullptr&&temp2!=nullptr){
                if(temp1->val<=temp2->val){
                    tmp->next=temp1;
                    temp1=temp1->next;
                }else{
                    tmp->next=temp2;
                    temp2=temp2->next;
                }
                tmp=tmp->next;
            }
            if(temp1!=nullptr)tmp->next=temp1;
            else if(temp2!=nullptr)tmp->next=temp2;
            return dummyHead->next;
        }
    };
  • 相关阅读:
    工作笔记之20170223:①关于Html5的placeholder属性,②以及input的outline:none的样式问题
    工作笔记之:如何在eclipse安装CVS插件?找了很久的,自己总结一下
    ajax后台请求两种方法(js和jQuery)
    22
    21
    20
    19
    18
    17
    16
  • 原文地址:https://www.cnblogs.com/qingjiuling/p/14017450.html
Copyright © 2011-2022 走看看