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;
        }
    };
  • 相关阅读:
    RabbitMQ简介、特性、使用场景、安装、启动与关闭
    mybatis的工作原理
    bzoj2119 股市的预测
    Noi2014 购票
    51Nod 算法马拉松22 开黑记
    COGS2485 从零开始的序列
    Codeforces Round #402 (Div.2)
    BestCoder Round #92
    COGS2294 释迦
    bzoj4764 弹飞大爷
  • 原文地址:https://www.cnblogs.com/qingjiuling/p/14017450.html
Copyright © 2011-2022 走看看