LeetCode 158 排序链表

LeetCode 158 排序链表

问题描述:
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
递归归并排序

执行用时:3 ms, 在所有 Java 提交中击败了99.15%的用户
内存消耗:41.7 MB, 在所有 Java 提交中击败了81.05%的用户

class Solution {
    public ListNode sortList(ListNode head) {
        /*递归终止*/
        if (head == null || head.next == null)
            return head;
        /*快慢指针找中点,将链表切断*/
        ListNode fast = head.next, slow = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode tmp = slow.next;
        slow.next = null;
        /*对拆分后的两部分进行排序*/
        ListNode left = sortList(head);
        ListNode right = sortList(tmp);
        ListNode h = new ListNode(0);
        ListNode res = h;
        /*合并两个有序链表*/
        while (left != null && right != null) {
            if (left.val < right.val) {
                h.next = left;
                left = left.next;
            } else {
                h.next = right;
                right = right.next;
            }
            h = h.next;
        }
        h.next = left != null ? left : right;
        /*返回合并后的有序链表*/
        return res.next;
    }
}
原文地址:https://www.cnblogs.com/CodeSPA/p/13550952.html