LeetCode 148.Sort List 鏈表排序

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

題目大意
對一個鏈表進行排序,複雜度在O(nlogn)內。
思路
我寫的是歸併排序,注意分開後的左邊鏈表的尾結點的next置null。


public class SortList {
    public ListNode sortList(ListNode head) {
        if ( head==null || head.next==null ) return head; 
        ListNode h1 = head;
        ListNode middle = getMiddle(head);

        ListNode h2 = middle.next;
        middle.next = null;
        return mergerList( sortList(h1), sortList(h2) );
    }

    private ListNode getMiddle(ListNode head ) {
        ListNode slow = head;
        ListNode fast = head; 
        while ( fast.next!=null && fast.next.next!=null ) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow; 
    }

    private ListNode mergerList(ListNode h1,ListNode h2) {
        ListNode head = new ListNode(-1);
        ListNode cur = head; 

        while ( h1!=null && h2!=null ) {
            if ( h1.val<=h2.val ) {
                cur.next = h1;
                h1 = h1.next;
            } else {
                cur.next = h2;
                h2 = h2.next;
            }
            cur = cur.next;
        }
        cur.next = (h1!=null)?h1:h2;
        return head.next;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章