力扣---143. 重排链表

发布时间 2023-07-31 10:58:53作者: Owlwu

给定一个单链表 L 的头节点 head ,单链表 L 表示为:

L0 → L1 → … → Ln - 1 → Ln

请将其重新排列后变为:

L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …

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

 

示例 1:

输入:head = [1,2,3,4]
输出:[1,4,2,3]

示例 2:

输入:head = [1,2,3,4,5]
输出:[1,5,2,4,3]

 

提示:

  • 链表的长度范围为 [1, 5 * 104]
  • 1 <= node.val <= 1000

 

快慢指针加反转链表加链表合并。

先来个栈版本

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public void reorderList(ListNode head) {
        if (head == null || head.next == null) {
            return;
        }
        ListNode p1 = head;
        ListNode p2 = head;
        while (p2 != null && p2.next != null) {
            p1 = p1.next;
            p2 = p2.next.next;
        }
        ListNode current = p1.next;
        p1.next = null;
        Deque<ListNode> deque = new ArrayDeque<>();
        while (current != null) {
            deque.addLast(current);
            current = current.next;
        }
        while (!deque.isEmpty()) {
            ListNode node = deque.removeLast();
            node.next = head.next;
            head.next = node;
            head = node.next;
        }
    }
}

 

反转链表:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public void reorderList(ListNode head) {
        if (head == null || head.next == null) {
            return;
        }
        ListNode p1 = head;
        ListNode p2 = head;
        while (p2 != null && p2.next != null) {
            p1 = p1.next;
            p2 = p2.next.next;
        }
        ListNode current = p1.next;
        p1.next = null;
        p2 = null;
        // 反转链表
        while (current != null) {
            ListNode next = current.next;
            current.next = p2;
            p2 = current;
            current = next;
        }
        while (p2 != null) {
            ListNode node = p2;
            p2 = p2.next;
            node.next = head.next;
            head.next = node;
            head = node.next;
        }
    }
}