225 用队列实现栈
题目225 用队列实现栈
思路
两个方法:分别是一个队列模拟栈和两个队列模拟栈
一个队列模拟栈
当栈pop时,只要把队列的前size-1个元素依次放入到队列末尾即可
代码
class MyStack:
# 使用一个队列实现栈
def __init__(self):
self.queue = []
def push(self, x: int) -> None:
self.queue.append(x)
def pop(self) -> int:
self.queue_len = len(self.queue)
for i in range(self.queue_len - 1):
self.queue.append(self.queue.pop(0))
return self.queue.pop(0)
def top(self) -> int:
return self.queue[-1]
def empty(self) -> bool:
return self.queue == []
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()