华为 OD 训练营 · 题解精讲
LeetCode225、用队列实现栈
LeetCode225、用队列实现栈
题目描述
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。 实现 MyStack 类: void push(int x) 将元素 x 压入栈顶。 int pop() 移除并返回栈顶元素。 int top() 返回栈顶元素。 boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
注意: 你只能使用队列的标准操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 这些操作。 你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
示例: 输入: ["MyStack", "push", "push", "top", "pop", "empty"] [[], [1], [2], [], [], []] 输出: [null, null, null, 2, 2, false]
解释: MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // 返回 2 myStack.pop(); // 返回 2 myStack.empty(); // 返回 False
提示: 1 <= x <= 9 最多调用100 次 push、pop、top 和 empty 每次调用 pop 和 top 都保证栈不为空
题目解析
参考代码(许老师)
1、Java 代码 class MyStack { Deque<Integer> q1; Deque<Integer> q2;
public MyStack() { q1 = new ArrayDeque<>(); q2 = new ArrayDeque<>(); }
public void push(int x) { q2.offer(x); while (!q1.isEmpty()) { int ele = q1.poll(); q2.offer(ele); } q1 = q2; q2 = new ArrayDeque<>(); }
public int pop() { return q1.poll(); }
public int top() { return q1.peek(); }
public boolean empty() { return q1.isEmpty(); } }
2、C++ 代码 class MyStack { private: queue<int> q1; queue<int> q2;
public: MyStack() {}
void push(int x) { q2.push(x); while (!q1.empty()) { q2.push(q1.front()); q1.pop(); } swap(q1, q2); }
int pop() { int front = q1.front(); q1.pop(); return front; }
int top() { return q1.front(); }
bool empty() { return q1.empty(); } };
3、Python 代码 class MyStack:
def __init__(self): self.q1 = deque() # 初始化两个队列q1和q2 self.q2 = deque() # q1为储存数据的主队列,q2为模拟栈过程的辅助队列
def push(self, x: int) -> None: self.q2.append(x) # 开始时q2为空,往q2中加入元素x while(self.q1): # 弹出q1队头元素,加入q2队尾,直到q1为空 ele = self.q1.popleft() self.q2.append(ele)
此时q2中就是出栈顺序了,为了维持q1是数据栈的角色,交换q1和q2
self.q1, self.q2 = self.q2, self.q1
def pop(self) -> int: return self.q1.popleft()
def top(self) -> int: return self.q1[0]
def empty(self) -> bool: return not self.q1