【LeetCode】 66 排序链表

行业解决方案、产品招募中!想赚钱就来传!>>> hot3.png

题目:

对于链表相关的代码初始化、遍历、添加还不熟练

【LeetCode】 66 排序链表_第1张图片

【LeetCode】 66 排序链表_第2张图片

解题思路:

归并排序(递归法)

【LeetCode】 66 排序链表_第3张图片

https://leetcode-cn.com/problems/sort-list/solution/sort-list-gui-bing-pai-xu-lian-biao-by-jyd/

代码:

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;
    }
}

你可能感兴趣的:(链表,leetcode,java,算法,bug)