首页 > 其他 > 详细

LeetCode143. 重排链表

时间:2020-12-14 23:59:46      阅读:26      评论:0      收藏:0      [点我收藏+]

技术分享图片

思路:

  1. 快慢指针找到中间节点,切成两半。(注意链表长度的奇偶性)
  2. 后半部分 reverse 操作。
  3. 归并操作,即后半部分 塞到 前半部分的“缝隙”里,组成新的链表。
class Solution {
    public void reorderList(ListNode head) {
        if (head == null || head.next == null) return;
        // Step1. 找到中间节点
        ListNode fast = head, slow = head;
        while (fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }

        // Step2:切成两半,后半部分reverse
        ListNode l2 = slow.next;
        slow.next = null;
        l2 = reverse(l2);
        ListNode l1 = head;

        // Step3:后半部分塞到 前半部分的"缝隙"里
        while (l1 != null && l2 != null) {
            ListNode next1 = l1.next;
            l1.next = l2;
            ListNode next2 = l2.next;
            l2.next = next1;

            l1 = next1;
            l2 = next2;
        }
    }
    // 反转链表
    private ListNode reverse(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode cur = head;
        ListNode pre = null, next = null;
        while (cur != null) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}

 

LeetCode143. 重排链表

原文:https://www.cnblogs.com/HuangYJ/p/14135688.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!