From 5daf942cd584259762907c1e796ad535d5aa9ce6 Mon Sep 17 00:00:00 2001 From: Lozakaka <102352821+Lozakaka@users.noreply.github.com> Date: Wed, 29 Mar 2023 22:47:54 -0400 Subject: [PATCH] =?UTF-8?q?Update=200225.=E7=94=A8=E9=98=9F=E5=88=97?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E6=A0=88.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增一個java solution用的是卡哥的邏輯 --- problems/0225.用队列实现栈.md | 37 +++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/problems/0225.用队列实现栈.md b/problems/0225.用队列实现栈.md index 16b9e47c..66d807c1 100644 --- a/problems/0225.用队列实现栈.md +++ b/problems/0225.用队列实现栈.md @@ -324,6 +324,43 @@ class MyStack { } } +``` +优化,使用一个 Queue 实现,但用卡哥的逻辑实现 +``` +class MyStack { + Queue queue; + + public MyStack() { + queue = new LinkedList<>(); + } + + public void push(int x) { + queue.add(x); + } + + public int pop() { + rePosition(); + return queue.poll(); + } + + public int top() { + rePosition(); + int result = queue.poll(); + queue.add(result); + return result; + } + + public boolean empty() { + return queue.isEmpty(); + } + + public void rePosition(){ + int size = queue.size(); + size--; + while(size-->0) + queue.add(queue.poll()); + } +} ``` Python: