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

版权声明:本文为Peppermint__原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。