zoukankan      html  css  js  c++  java
  • 链表归并排序

    题目描述
    在O(n log n)的时间内使用常数级空间复杂度对链表进行排序。
    示例1
    输入
    复制
    {30,20,40}
    返回值
    复制
    {20,30,40}
    说明:本题目包含复杂数据结构ListNode,点此查看相关信息

    
    
    #define null NULL
    #define Node ListNode
    
    class Solution {
    public:
        /**
         * 
         * @param head ListNode类 
         * @return ListNode类
         */
        ListNode* sortList(ListNode* head) {
            // write code here
            if(head) return getMiddle(head);
            return null;
        }
    //     int len(Node* h) {
    //         int x=0;
    //         while(h)x++,h=h->next;
    //         return x;
    //     }
        Node* getMiddle(ListNode* head) {
            if(head==null||head->next==null) return head;
            Node* first=head,*last=head,*pre=null;
            while(first && first->next) first=first->next->next,pre = last, last=last->next;
            pre->next=NULL;
            Node* l = getMiddle(head);
            Node* r = getMiddle(last);
            return merge(l,r);
            
        }
        Node* merge(Node* l, Node* r) {
            if(l==null) return r;
            if(r==null) return l;
            Node dummy(0);
            Node* first = &dummy, *last = first;
            while(l && r) {
                if(l->val <= r->val) last->next = l,l=l->next,last=last->next,last->next=null;
                else last->next=r,r=r->next,last = last->next,last->next=null;
            }
            if(l)last->next = l;
            if(r)last->next=r;
            return first->next;
        }
    };
    
    
  • 相关阅读:
    iOS开发UI篇—使用storyboard创建导航控制器以及控制器的生命周期
    IOS开发UI篇—导航控制器属性和基本使用
    基于XMPP协议的aSmack源码分析
    XMPP-for-Android
    wecontact
    MyPhone
    Video conference server OpenMCU-ru
    WebRTC_Wrapper
    Sip-MCU
    WebRTC学习笔记
  • 原文地址:https://www.cnblogs.com/lyr-2000/p/14323128.html
Copyright © 2011-2022 走看看