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;
        }
    };
    
    
  • 相关阅读:
    oracle timestamp的转换
    sql总结
    shell命令记录一些
    练手之 合并排序
    jquery的笔记
    jquery的几个小例子
    【转】JQUERY相关的几个网站
    hibernate spring sturts2配置
    oracle积累继续
    2018.8.21 2018暑假集训之方格取数
  • 原文地址:https://www.cnblogs.com/lyr-2000/p/14323128.html
Copyright © 2011-2022 走看看