L148. Sort List

LinkedList

Problem:

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

Example 1:

Input: 4->2->1->3
Output: 1->2->3->4

Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5

Solution:

  • O(n log n) time

  • two functions: findMid and merge

  • findMid: slow moves 1 step, fast moves 2 steps/// cut the list in half

  • merge

    public ListNode sortList(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode pre = findMid(head);
        ListNode next = pre.next;
        pre.next = null;
        ListNode h1 = sortList(head);
        ListNode h2 = sortList(next);
        ListNode newHead = merge(h1, h2);
        return newHead;
    }
    public ListNode findMid(ListNode head){
        ListNode pre = null;
        ListNode slow = head;
        ListNode fast = head;
        while(fast != null && fast.next != null){
            pre = slow;
            slow = slow.next;
            fast = fast.next.next;
        }
        return pre;
    }
    public ListNode merge(ListNode h1, ListNode h2){
        if(h1 == null) return h2;
        if(h2 == null) return h1;
        if(h1.val < h2.val){
            h1.next = merge(h1.next, h2);
            return h1;
        }else{
            h2.next = merge(h1, h2.next);
            return h2;
        }
    }

Last updated

Was this helpful?