链表续

作者: couriravant | 来源:发表于2019-12-26 01:24 被阅读0次

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

    相关文章

      网友评论

          本文标题:链表续

          本文链接:https://www.haomeiwen.com/subject/ywahoctx.html