Sort List

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

Example

Given1->3->2->null, sort it to1->2->3->null.

public ListNode sortList(ListNode head) {
    if(head == null || head.next == null) {
        return head;
    }
    ListNode slow = head, fast = head;
    while(fast.next != null && fast.next.next != null) {
        slow = slow.next;
        fast = fast.next.next;
    }
    ListNode p1 = head, p2 = slow.next;
    slow.next = null;
    ListNode left = sortList(p1);
    ListNode right = sortList(p2);
    return merge(left, right);
}

public ListNode merge(ListNode l1, ListNode l2) {
    if(l1 == null) {
        return l2;
    }
    if(l2 == null) {
        return l1;
    }
    ListNode dummy = new ListNode(-1);
    ListNode p = dummy;
    while(l1 != null && l2 != null) {
        if(l1.val < l2.val) {
            p.next = l1;
            l1 = l1.next;
        }
        else {
            p.next = l2;
            l2 = l2.next;
        }
        p = p.next;
    }
    if(l1 == null) {
        p.next = l2;
    }
    if(l2 == null) {
        p.next = l1;
    }
    return dummy.next;
}

results matching ""

    No results matching ""