链表续

2019-12-26  本文已影响0人  couriravant

148. 排序链表

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;
      //head、temp分别是左右两个链表的头节点
        ListNode left = sortList(head);
        ListNode right = sortList(tmp);
      //放一个临时节点把左右两个已排序链表合并
        ListNode h = new ListNode(0);
        ListNode res = h;
        System.out.println(res.val);
        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;
        }
     //  left和right哪个是最后没被h.next加入的,给加入
        h.next = left != null ? left : right;
        System.out.println(res.val);
        return res.next;

    }
上一篇下一篇

猜你喜欢

热点阅读