LeetCode-143.重排链表(相关话题:快慢指针)

给定一个单链表 L:L0→L1→…→Ln-1→Ln , 将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例 1:

给定链表 1->2->3->4, 重新排列为 1->4->2->3.

示例 2:

给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.

解题思路:

  1. 快慢指针找到中点,分为前半部分和后半部分两个链表
  2. 将后半部分的链表反转
  3. 将前半部分链表和后半部分链表间隔插入

Java代码:

class Solution {
    public void reorderList(ListNode head) {
        ListNode slow = head, fast = head, p, q, tmp = new ListNode(0x3FFFFF);
        tmp.next = head;
        while (null != fast && null != fast.next) {
            tmp = tmp.next;
            slow = slow.next;
            fast = fast.next.next;
        }
        tmp.next = null;

        fast = slow;
        slow = null;
        while (null != fast) {
            p = slow;
            slow = fast;
            fast = fast.next;
            slow.next = p;
        }

        fast = head;
        while (null != slow && null != fast) {
            p = fast.next;
            q = slow.next;
            fast.next = slow;
            slow.next = p;
            tmp = slow;
            fast = p;
            slow = q;
        }
        tmp.next = slow;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_38823568/article/details/87856214