1. 程式人生 > >leetcode148 連結串列排序

leetcode148 連結串列排序

在 O(n log n) 時間複雜度和常數級空間複雜度下,對連結串列進行排序。

使用歸併排序

public ListNode sortList(ListNode head) {
    if(head == null || head.next == null) return head;
    ListNode slow = head;
    ListNode pre = head;
    ListNode fast = head;
    while(fast != null && fast.next != null){
        // 找出中間節點,無論奇偶數節點,pre都停留在中間的前一個
        // slow會停在中間或中間的後一個
        pre = slow;
        slow = slow.next;
        fast = fast.next.next;
    }
    pre.next = null;
    return merge(sortList(head), sortList(slow));
}
public ListNode merge(ListNode l1, ListNode l2){
    if(l1 == null) return l2;
    if(l2 == null) return l1;
    if(l1.val < l2.val){
        l1.next = merge(l1.next, l2);
        return l1;
    }else{
        l2.next = merge(l1, l2.next);
        return l2;
    }
}