From 425593d78230462ede74c026fab8b119564c8ea1 Mon Sep 17 00:00:00 2001 From: bourne-3 <595962708@qq.com> Date: Mon, 6 Sep 2021 22:16:23 +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?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0143.重排链表.md | 41 +++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/problems/0143.重排链表.md b/problems/0143.重排链表.md index 76df63b7..62d4cb3f 100644 --- a/problems/0143.重排链表.md +++ b/problems/0143.重排链表.md @@ -219,6 +219,47 @@ public class ReorderList { return headNode.next; } } + +------------------------------------------------------------------------- +// 方法一 Java实现,使用数组存储节点 + class Solution { + public void reorderList(ListNode head) { + // 双指针的做法 + ListNode cur = head; + // ArrayList底层是数组,可以使用下标随机访问 + List list = new ArrayList<>(); + while (cur != null){ + list.add(cur); + cur = cur.next; + } + cur = head; // 重新回到头部 + int l = 1, r = list.size() - 1; // 注意左边是从1开始 + int count = 0; + while (l <= r){ + if (count % 2 == 0){ + // 偶数 + cur.next = list.get(r); + r--; + }else { + // 奇数 + cur.next = list.get(l); + l++; + } + // 每一次指针都需要移动 + cur = cur.next; + count++; + } + // 当是偶数的话,需要做额外处理 + if (list.size() % 2== 0){ + cur.next = list.get(l); + cur = cur.next; + } + + // 注意结尾要结束一波 + cur.next = null; + } +} + ``` Python: