zoukankan      html  css  js  c++  java
  • 【链表】Sort List(归并排序)

    题目:

    Sort a linked list in O(n log n) time using constant space complexity.

    思路:

    nlogn的排序有快速排序、归并排序、堆排序。双向链表用快排比较适合,堆排序也可以用于链表,单向链表适合用归并排序。

    /**
     * Definition for singly-linked list.
     * function ListNode(val) {
     *     this.val = val;
     *     this.next = null;
     * }
     */
    /**
     * @param {ListNode} head
     * @return {ListNode}
     */
    var sortList = function(head) {
        if(head==null||head.next==null){
            return head;
        }else{
            var slow=head,fast=head;
            while(fast.next!=null&&fast.next.next!=null){
                slow=slow.next;
                fast=fast.next.next;
            }
            //拆成两个链表
            fast=slow;
            slow=slow.next;
            fast.next=null;
            
            fast=sortList(head);
            slow=sortList(slow);
            return merge(fast,slow);
        }
    };
    
    function merge(head1,head2){
        if(head1==null){
            return head2;
        }
        if(head2==null){
            return head1;
        }
        var res=new ListNode(),p=new ListNode();
        if(head1.val<head2.val){
            res=head1;
            head1=head1.next;
        }else{
            res=head2;
            head2=head2.next;
        }
        p=res;
        
        while(head1!=null&&head2!=null){
            if(head1.val<head2.val){
                p.next=head1;
                head1=head1.next;
            }else{
                p.next=head2;
                head2=head2.next;
            }
            p=p.next;
        }
        
        if(head1!=null){
            p.next=head1;
        }else if(head2!=null){
            p.next=head2;
        }
        
        return res;
    }
  • 相关阅读:
    python yield yield from
    python isinstance()与type()的区别
    python isinstance用法
    python 展开嵌套的序列
    python getmtime() 最近修改文件内容的时间
    python getctime() 文件最后一次的改变时间
    python getatime() 查看文件的访问时间
    python模拟随机游走
    getopt例子
    matplotlib 代码风格
  • 原文地址:https://www.cnblogs.com/shytong/p/5142698.html
Copyright © 2011-2022 走看看