zoukankan      html  css  js  c++  java
  • 148. Sort List

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

     双链表用快排 单链表用归并

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
     
     //归并
    public class Solution {
        public ListNode sortList(ListNode head) {
            if(head == null || head.next == null){
                return head;
            }
            ListNode dummy = head;
            ListNode fast = head;
            ListNode slow = head;
            while(fast != null && fast.next != null){
                dummy = slow;
                slow = slow.next;
                fast = fast.next.next;
            }
            dummy.next = null; // 断开 两条list
            ListNode l1 = sortList(head);
            ListNode l2 = sortList(slow);
            return mergeLists(l1,l2);
        }
        public ListNode mergeLists(ListNode l1, ListNode l2){
            if(l1 == null && l2 == null)
                return null;
            if(l1 == null)  
                return l2;
            if(l2 == null)
                return l1;
            if(l1.val > l2.val){
                l2.next = mergeLists(l1, l2.next);
                return l2;
            }
            else{
                l1.next = mergeLists(l1.next, l2);
                return l1;
            }
        }
    }
  • 相关阅读:
    CSS实现小三角小技巧
    Javascript原型继承 __proto__
    99乘法表
    函数式编程之纯函数
    函数式编程 本质(笔记)转载
    函数式编程之柯里化(curry)
    Javascript-常用字符串数组操作
    第十章
    第九章
    第八章读后感
  • 原文地址:https://www.cnblogs.com/joannacode/p/6009913.html
Copyright © 2011-2022 走看看