From a95b24a2290c72197e9107e38e91e11ffa92ef3d Mon Sep 17 00:00:00 2001 From: SianXiaoCHN Date: Thu, 17 Mar 2022 13:43:03 -0500 Subject: [PATCH] =?UTF-8?q?0225.=E7=94=A8=E9=98=9F=E5=88=97=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0=E6=A0=88=20python3=20=E6=9B=B4=E6=96=B0=E4=BC=98?= =?UTF-8?q?=E5=8C=96=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0225.用队列实现栈 python3 更新优化方法(只使用一个队列) --- problems/0225.用队列实现栈.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/problems/0225.用队列实现栈.md b/problems/0225.用队列实现栈.md index c45917db..3457c4b3 100644 --- a/problems/0225.用队列实现栈.md +++ b/problems/0225.用队列实现栈.md @@ -354,6 +354,32 @@ class MyStack: return len(self.queue_in) == 0 ``` +优化,使用一个队列实现 +```python +class MyStack: + + def __init__(self): + self.que = deque() + + def push(self, x: int) -> None: + self.que.append(x) + + def pop(self) -> int: + if self.empty(): + return None + for i in range(len(self.que)-1): + self.que.append(self.que.popleft()) + return self.que.popleft() + + def top(self) -> int: + if self.empty(): + return None + return self.que[-1] + + def empty(self) -> bool: + return not self.que +``` + Go: