Merge pull request #696 from GHumorBS/patch-1

Update 0232.用栈实现队列.md
This commit is contained in:
程序员Carl
2021-09-02 08:51:09 +08:00
committed by GitHub

View File

@ -205,33 +205,26 @@ class MyQueue:
def pop(self) -> int: def pop(self) -> int:
""" """
1. 检查如果out里面元素则直接pop Removes the element from in front of queue and returns that element.
2. 如果out没有元素就把in里面的元素除了第一个依次pop后装进out里面
3. 直接把in剩下的元素pop出来就是queue头部的
""" """
if self.empty: if self.empty():
return None return None
if self.stack_out: if self.stack_out:
return self.stack_out.pop() return self.stack_out.pop()
else: else:
for i in range(1, len(self.stack_in)): for i in range(len(self.stack_in)):
self.stack_out.append(self.stack_in.pop()) self.stack_out.append(self.stack_in.pop())
return self.stack_in.pop() return self.stack_out.pop()
def peek(self) -> int: def peek(self) -> int:
""" """
1. 查out有没有元素有就把最上面的返回 Get the front element.
2. 如果out没有元素就把in最下面的返回
""" """
if self.empty: ans = self.pop()
return None self.stack_out.append(ans)
return ans
if self.stack_out:
return self.stack_out[-1]
else:
return self.stack_in[0]
def empty(self) -> bool: def empty(self) -> bool: