题目
使用队列实现栈的下列操作:
- push(x)— 元素x入栈
- pop() — 移除栈顶元素
- top()— 获取栈顶元素
- empty() — 返回栈是否为空
思路
队列:先入先出
栈: 先入后出
核心在于每次新元素入队之后,要更改顺序。
class MyStack:def __init__(self):"""Initialize your data structure here."""self.queue1 = collections.deque() # 存储栈元素self.queue2 = collections.deque() # 用于入栈def push(self, x: int) -> None:"""Push element x onto stack."""self.queue2.append(x)while self.queue1:# 让栈中的元素依次放在后面self.queue2.append(self.queue1.popleft())self.queue1, self.queue2 = self.queue2, self.queue1def pop(self) -> int:"""Removes the element on top of the stack and returns that element."""return self.queue1.popleft()def top(self) -> int:"""Get the top element."""return self.queue1[0]def empty(self) -> bool:"""Returns whether the stack is empty."""return not self.queue1
