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

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

    O(n lg n) constant space的常见sort方法有 merge sort, quick sort, heap sort。 quick sort 需要random choose 哨兵,Merge更加适合linked list。注意对半分的时候不要忘了将左半边的tail变为null。

    public ListNode SortList(ListNode head) {
             if (head == null || head.next == null)
                return head;
                
               // step 1. cut the list to two halves
            ListNode prev = null, slow = head, fast = head; 
            
            while (fast != null && fast.next != null) {
          prev = slow;
          slow = slow.next;
          fast = fast.next.next;
        }
            prev.next = null;
             // step 2. sort each half
        ListNode l1 = SortList(head);
        ListNode l2 = SortList(slow);
    
        // step 3. merge l1 and l2
        return Merge(l1, l2);
            
        }
        
        private ListNode Merge(ListNode left, ListNode right )
        {
           
            ListNode stand = new ListNode(0);
            ListNode l = stand;
            while( left!= null && right != null)
            {
                if(left.val < right.val)
            {
                l.next = left;
                left = left.next;
            }
            else
            {
                l.next = right;
                right = right.next;
            }
            l = l.next;
            }
            
             if (left != null)
            l.next = left;
    
            if (right != null)
            l.next = right;
            return stand.next;
        }
  • 相关阅读:
    spring.jar的下载地址
    spring学习(1)
    供求信息网(2)
    编写学生增删改查系统时碰到的问题
    js中innerText/value/innerHTML三个属性的区别
    form的提交方式
    错误记录(1)
    供求信息网
    GYM 101673F(树计数)
    GYM 101673G(dp)
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5867245.html
Copyright © 2011-2022 走看看