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 +