mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
0225.用队列实现栈 python3 更新优化方法
0225.用队列实现栈 python3 更新优化方法(只使用一个队列)
This commit is contained in:
@ -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:
|
||||
|
||||
|
Reference in New Issue
Block a user