From 680cf3dbd74d4266d1a077c493d0c440fd6bebfb Mon Sep 17 00:00:00 2001 From: Flow-sandyu <72751523+Flow-sandyu@users.noreply.github.com> Date: Wed, 5 Oct 2022 10:12:19 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=200225.=E7=94=A8=E9=98=9F?= =?UTF-8?q?=E5=88=97=E5=AE=9E=E7=8E=B0=E6=A0=88.md=20java=20=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 优化,使用一个 Queue 实现 对比 『使用一个 Deque 实现』 的解法,我把移动元素的代码放到 push 方法里,代码看起来更简洁 --- problems/0225.用队列实现栈.md | 34 +++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/problems/0225.用队列实现栈.md b/problems/0225.用队列实现栈.md index fb2851f1..4412a819 100644 --- a/problems/0225.用队列实现栈.md +++ b/problems/0225.用队列实现栈.md @@ -292,6 +292,40 @@ class MyStack { } ``` +优化,使用一个 Queue 实现 +```java +class MyStack { + + Queue queue; + + public MyStack() { + queue = new LinkedList<>(); + } + + //每 offer 一个数(A)进来,都重新排列,把这个数(A)放到队列的队首 + public void push(int x) { + queue.offer(x); + int size = queue.size(); + //移动除了 A 的其它数 + while (size-- > 1) + queue.offer(queue.poll()); + } + + public int pop() { + return queue.poll(); + } + + public int top() { + return queue.peek(); + } + + public boolean empty() { + return queue.isEmpty(); + } +} + +``` + Python: ```python