算法 - 归并排序

算法 - 归并排序

递归法

  1. 使用快慢指针,找到中间节点,当只有一个节点的时候,递归失效。
  2. 递归左部节点的头节点和右部节点的头节点。
  3. 新建前驱节点,并创建指向前驱节点的头指针,对比左右两侧节点大小,然后插入到前驱节点。

参考代码

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;//返回虚拟头节点的下一个
    }
}
posted @ 2022-03-05 11:24  护发师兄  阅读(26)  评论(0编辑  收藏  举报