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; + } +} ```