Sort List(链表排序)

问题

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

Have you met this question in a real interview? Yes
Example
Given 1->3->2->null, sort it to 1->2->3->null.

代码

/**
 * Definition for ListNode.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode(int val) {
 * this.val = val;
 * this.next = null;
 * }
 * }
 */
public class Solution {
    /**
     * @param head: The head of linked list.
     * @return: You should return the head of the sorted linked list,
     * using constant space complexity.
     */
    public ListNode sortList(ListNode head) {
        // write your code here
        if (head == null || head.next == null) {
            return head;
        }
        ListNode middle = findMiddle(head);
        //用递归减少复杂性
        ListNode right = sortList(middle.next);
        //需要把链表分开成两部分。
        middle.next = null;
        ListNode left = sortList(head);

        return merge(left, right);
    }

    //标准的归并
    private ListNode merge(ListNode left, ListNode right) {
        ListNode dummy = new ListNode(0);
        ListNode temp = dummy;
        while (left != null && right != null) {
            if (left.val > right.val) {
                temp.next = right;
                right = right.next;
            } else {
                temp.next = left;
                left = left.next;
            }
            temp = temp.next;
        }
        if (left == null) {
            temp.next = right;
        } else {
            temp.next = left;
        }
        return dummy.next;
    }

    private ListNode findMiddle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head.next;
        //用一快一慢两个指针,快的一次身后偏移两位,慢的一次向后偏移一位,去找中点。
        while (fast != null && fast.next != null) {
            //slow会比较慢,所以只需要用fast作为中止循环的条件即可。
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }
}

你可能感兴趣的:(Sort List(链表排序))