Problem

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

Example
Given 1->3->2->null, sort it to 1->2->3->null.

思路

  • merge sort
  • split the list into two halves
  • sort them, and merge them
  • if the list just contains one element, just return that element.
    public ListNode sortList(ListNode head) {  
        if (head == null || head.next == null) {
            return head;
        }
        ListNode mid = findMid(head);
        ListNode midNext = mid.next;
        mid.next = null;
        ListNode l1 = sortList(head);
        ListNode l2 = sortList(midNext);
        return mergeTwoSortedLists(l1, l2);
    }

    private ListNode findMid(ListNode head) {
        ListNode slow = head;
        ListNode fast = head.next;

        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

    private ListNode mergeTwoSortedLists(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode curt = dummy;

        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                curt.next = l1;
                l1 = l1.next;
            } else {
                curt.next = l2;
                l2 = l2.next;
            }
            curt = curt.next;
        }
        if (l1 != null) {
            curt.next = l1;
        }
        if (l2 != null) {
            curt.next = l2;
        }
        return dummy.next;
    }

results matching ""

    No results matching ""