Sort List

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

Analysis

  1. Function to merge two sorted lists
  2. Main function sortList:
    1. use slow/faster pointer to find mid node
    2. break lists into two lists
    3. sort 1st half and second half
    4. merge two lists

Code

public class Solution {
    public ListNode sortList(ListNode head) {
        if(head==null || head.next==null) {return head;}

        ListNode mid = findMid(head);

        ListNode rhead = mid.next;
        ListNode lhead = head;
        mid.next = null;

        lhead = sortList(lhead);
        rhead = sortList(rhead);

        ListNode res = mergeLists(lhead, rhead);

        return res;

    }

    private ListNode findMid(ListNode head){
        if (head == null || head.next==null) {return head;}
        ListNode slow = head, fast = head.next;
        while (fast!=null && fast.next!=null){
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

    private ListNode mergeLists(ListNode l1, ListNode l2){
        ListNode dummy = new ListNode(0);
        ListNode curr = dummy;
        while( (l1!=null) && (l2!=null)){
            if(l1.val>l2.val){
                curr.next = l2;
                l2 = l2.next;
            }
            else {
                curr.next = l1;
                l1 = l1.next;
            }
            curr=curr.next;
        }

        curr.next = (l1!=null)?l1:l2;

        return dummy.next;
    }

}

Note

  • Merge sort要掌握好
  • Merge 2 lists要掌握好
  • Find mid要掌握好

Reference