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: