更新 0232.用栈实现队列.md python代码

python代码简化,符合PEP8标准,可读性加强,效率提升
This commit is contained in:
Eyjan_Huang
2021-08-20 00:06:33 +08:00
committed by GitHub
parent 1a82f98a17
commit a69006f901

View File

@ -281,48 +281,54 @@ class MyQueue {
Python
```python
# 使用两个栈实现先进先出的队列
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
in主要负责pushout主要负责pop
"""
self.stack1 = list()
self.stack2 = list()
self.stack_in = []
self.stack_out = []
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
有新元素进来就往in里面push
"""
# self.stack1用于接受元素
self.stack1.append(x)
self.stack_in.append(x)
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
1. 检查如果out里面元素则直接pop
2. 如果out没有元素就把in里面的元素除了第一个依次pop后装进out里面
3. 直接把in剩下的元素pop出来就是queue头部的
"""
# self.stack2用于弹出元素如果self.stack2为[],则将self.stack1中元素全部弹出给self.stack2
if self.stack2 == []:
while self.stack1:
tmp = self.stack1.pop()
self.stack2.append(tmp)
return self.stack2.pop()
if self.stack_out:
return self.stack_out.pop()
else:
for i in range(1, len(self.stack_in)):
self.stack_out.append(self.stack_in.pop())
return self.stack_in.pop()
def peek(self) -> int:
"""
Get the front element.
1. 查out有没有元素有就把最上面的返回
2. 如果out没有元素就把in最下面的返回
"""
if self.stack2 == []:
while self.stack1:
tmp = self.stack1.pop()
self.stack2.append(tmp)
return self.stack2[-1]
if self.stack_out:
return self.stack_out[-1]
else:
return self.stack_in[0]
def empty(self) -> bool:
"""
Returns whether the queue is empty.
只要in或者out有元素说明队列不为空
"""
return self.stack1 == [] and self.stack2 == []
return not (self.stack_in or self.stack_out)
```