From cd7ef344e76cfb913256e65076de5d62cf47080c Mon Sep 17 00:00:00 2001 From: bourne-3 <595962708@qq.com> Date: Mon, 6 Sep 2021 22:36:27 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0java=E5=AE=9E=E7=8E=B0143?= =?UTF-8?q?=E9=87=8D=E6=8E=92=E9=93=BE=E8=A1=A8=E6=96=B9=E6=B3=95=E4=BA=8C?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0143.重排链表.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0143.重排链表.md b/problems/0143.重排链表.md index 62d4cb3f..2b4e68b7 100644 --- a/problems/0143.重排链表.md +++ b/problems/0143.重排链表.md @@ -177,6 +177,7 @@ public: Java: ```java +// 方法三 public class ReorderList { public void reorderList(ListNode head) { ListNode fast = head, slow = head; @@ -259,6 +260,35 @@ public class ReorderList { cur.next = null; } } +------------------------------------------------------------------------- +// 方法二:使用双端队列,简化了数组的操作,代码相对于前者更简洁(避免一些边界条件) +class Solution { + public void reorderList(ListNode head) { + // 使用双端队列的方法来解决 + Deque de = new LinkedList<>(); + // 这里是取head的下一个节点,head不需要再入队了,避免造成重复 + ListNode cur = head.next; + while (cur != null){ + de.offer(cur); + cur = cur.next; + } + cur = head; // 回到头部 + + int count = 0; + while (!de.isEmpty()){ + if (count % 2 == 0){ + // 偶数,取出队列右边尾部的值 + cur.next = de.pollLast(); + }else { + // 奇数,取出队列左边头部的值 + cur.next = de.poll(); + } + cur = cur.next; + count++; + } + cur.next = null; + } +} ```