queue_use_stack
queue_use_stack.py 源码
import sys
# 用栈实现队列
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.input = []
self.output = []
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self.input.append(x)
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
self.peek()
return self.output.pop()
def peek(self) -> int:
"""
Get the front element.
"""
if len(self.output) == 0:
while len(self.input) > 0:
self.output.append(self.input.pop())
return self.output[-1]
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
return len(self.input) == 0 and len(self.output) == 0
你可能感兴趣的文章
0
赞
热门推荐
-
2、 - 优质文章
-
3、 gate.io
-
8、 golang
-
9、 openharmony
-
10、 Vue中input框自动聚焦