LINKED LIST

排序链表

中等#148时间 O(n log n)空间 O(log n)力扣原题 ↗

题目

把链表按非递减顺序排序,要求 O(n log n) 时间。这里采用自顶向下归并排序,使用 O(log n) 递归空间。

示例输入head = [4,2,1,3]
示例输出[1,2,3,4]

思路

快慢指针找到中点,断开为两条链,分别递归排序,再通过移动节点连接合并两个有序结果。若严格要求 O(1) 辅助空间,可改用自底向上的迭代归并。

每一步都成立

merge 的两个输入都已排序,tail 前面的输出按非递减顺序排列。

看它一步步执行

用的是题目示例
数组 / nums步骤 1
执行状态
这次的结果播放到最后查看

Solution.java参考解法 · 高亮的是正在执行的行
1class Solution {2    public ListNode sortList(ListNode head) {3        if (head == null || head.next == null) return head;4        ListNode slow = head, fast = head.next;5        while (fast != null && fast.next != null) {6            slow = slow.next; fast = fast.next.next;7        }8        ListNode second = slow.next;9        slow.next = null;10        ListNode left = sortList(head);11        ListNode right = sortList(second);12        return merge(left, right);13    }14    private ListNode merge(ListNode a, ListNode b) {15        ListNode dummy = new ListNode(0), tail = dummy;16        while (a != null && b != null) {17            if (a.val <= b.val) {18                tail.next = a; a = a.next;19            } else {20                tail.next = b; b = b.next;21            }22            tail = tail.next;23        }24        tail.next = a == null ? b : a;25        return dummy.next;26    }27}
← → 单步 · 空格 播放
↑↓ 选择↵ 打开Pagefind 全文检索