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

    在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。

    示例 1:

    输入: 4->2->1->3
    输出: 1->2->3->4
    

    示例 2:

    输入: -1->5->3->4->0
    输出: -1->0->3->4->5


    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode sortList(ListNode head) {
            return head==null?null:mergeSort(head);
        }
        public ListNode mergeSort(ListNode head){
            if(head.next==null){
                return head;
            }
            ListNode p=head,q=head,pre=null;
            while(q!=null&&q.next!=null){
                pre=p;
                p=p.next;
                q=q.next.next;
            }
            pre.next=null;
            ListNode l=mergeSort(head);
            ListNode r=mergeSort(p);
            return merge(l,r);
        }
        public ListNode merge(ListNode l,ListNode r){
            ListNode dummyHead=new ListNode(0);
            ListNode cur=dummyHead;
            while(l!=null&&r!=null){
                if(l.val<r.val){
                    cur.next=l;
                    cur=cur.next;
                    l=l.next;
                }
                else{
                    cur.next=r;
                    cur=cur.next;
                    r=r.next;
                }
               
            }
            if(l!=null){
                cur.next=l;
            }
            if(r!=null){
                cur.next=r;
            }
            return dummyHead.next;
        }
    }
  • 相关阅读:
    满屏品字布局怎么设计
    Web前端面试题(二)
    Welcome-to-Swift-11方法(Methods)
    Welcome-to-Swift-10属性 (Properties)
    Welcome-to-Swift-09类和结构体(Classes and Structures)
    Welcome-to-Swift-08枚举 (Enumerations)
    Welcome-to-Swift-07闭包(Closures)
    Welcome-to-Swift-06函数(Functions)
    Welcome-to-Swift-05控制流(Control Flow )
    Welcome-to-Swift-04集合类型(Collection Types)
  • 原文地址:https://www.cnblogs.com/yihangZhou/p/10046258.html
Copyright © 2011-2022 走看看