From 3169bc2688d702a1b8b367a6cf94db1ef88bf345 Mon Sep 17 00:00:00 2001 From: Powerstot <77142630+Powerstot@users.noreply.github.com> Date: Tue, 18 May 2021 17:52:35 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B90225.=E7=94=A8=E9=98=9F?= =?UTF-8?q?=E5=88=97=E5=AE=9E=E7=8E=B0=E6=A0=88=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修改0225.用队列实现栈 Java版本 --- problems/0225.用队列实现栈.md | 90 ++++++++++++++++++++++++++++- 1 file changed, 89 insertions(+), 1 deletion(-) diff --git a/problems/0225.用队列实现栈.md b/problems/0225.用队列实现栈.md index 4018364a..8dff2b86 100644 --- a/problems/0225.用队列实现栈.md +++ b/problems/0225.用队列实现栈.md @@ -156,6 +156,7 @@ public: Java: +使用两个 Queue 实现 ```java class MyStack { @@ -205,7 +206,94 @@ class MyStack { * boolean param_4 = obj.empty(); */ ``` +使用两个 Deque 实现 +```java +class MyStack { + // Deque 接口继承了 Queue 接口 + // 所以 Queue 中的 add、poll、peek等效于 Deque 中的 addLast、pollFirst、peekFirst + Deque que1; // 和栈中保持一样元素的队列 + Deque que2; // 辅助队列 + /** Initialize your data structure here. */ + public MyStack() { + que1 = new ArrayDeque<>(); + que2 = new ArrayDeque<>(); + } + + /** Push element x onto stack. */ + public void push(int x) { + que1.addLast(x); + } + + /** Removes the element on top of the stack and returns that element. */ + public int pop() { + int size = que1.size(); + size--; + // 将 que1 导入 que2 ,但留下最后一个值 + while (size-- > 0) { + que2.addLast(que1.peekFirst()); + que1.pollFirst(); + } + int res = que1.pollFirst(); + // 将 que2 对象的引用赋给了 que1 ,此时 que1,que2 指向同一个队列 + que1 = que2; + // 如果直接操作 que2,que1 也会受到影响,所以为 que2 分配一个新的空间 + que2 = new ArrayDeque<>(); + return res; + } + + /** Get the top element. */ + public int top() { + return que1.peekLast(); + } + + /** Returns whether the stack is empty. */ + public boolean empty() { + return que1.isEmpty(); + } +} +``` +优化,使用一个 Deque 实现 +```java +class MyStack { + // Deque 接口继承了 Queue 接口 + // 所以 Queue 中的 add、poll、peek等效于 Deque 中的 addLast、pollFirst、peekFirst + Deque que1; + /** Initialize your data structure here. */ + public MyStack() { + que1 = new ArrayDeque<>(); + } + + /** Push element x onto stack. */ + public void push(int x) { + que1.addLast(x); + } + + /** Removes the element on top of the stack and returns that element. */ + public int pop() { + int size = que1.size(); + size--; + // 将 que1 导入 que2 ,但留下最后一个值 + while (size-- > 0) { + que1.addLast(que1.peekFirst()); + que1.pollFirst(); + } + + int res = que1.pollFirst(); + return res; + } + + /** Get the top element. */ + public int top() { + return que1.peekLast(); + } + + /** Returns whether the stack is empty. */ + public boolean empty() { + return que1.isEmpty(); + } +} +``` Python: @@ -276,4 +364,4 @@ Go: * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -
\ No newline at end of file +