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;
    }

 

posted @ 2016-09-13 09:20  咖啡中不塌缩的方糖  阅读(109)  评论(0编辑  收藏  举报