题目描述 225. Implement Stack using Queues
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push
, top
, pop
, and empty
).
Implement the MyStack
class:
void push(int x)
Pushes element x to the top of the stack.int pop()
Removes the element on the top of the stack and returns it.int top()
Returns the element on the top of the stack.boolean empty()
Returns true if the stack is empty, false otherwise.
Notes:
- You must use only standard operations of a queue, which means that only push to back, peek/pop from front, size and is empty operations are valid.
- Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue’s standard operations.
使用两个队列实现一个后进先出(LIFO)的栈。实现的栈需要支持普通栈的所有操作(push
、top
、pop
和 empty
)。
解题思路
- 使用两个队列
q1
和q2
来模拟栈的行为。 - 每次
push
操作时,将新元素加入非空队列中。 - 每次
pop
或top
操作时,将非空队列中的元素依次移动到另一个队列,直到剩下最后一个元素,该元素就是栈顶元素。 empty
操作只需检查两个队列是否都为空。
#include <queue>
class MyStack {
private:
queue<int> q1;
queue<int> q2;
public:
MyStack() {}
void push(int x) {
// 将新元素加入非空队列
if (!q1.empty()) {
q1.push(x);
} else {
q2.push(x);
}
}
int pop() {
// 找到非空队列
queue<int>& nonEmptyQueue = q1.empty() ? q2 : q1;
queue<int>& emptyQueue = q1.empty() ? q1 : q2;
// 将非空队列中的元素移动到空队列,直到剩下最后一个元素
while (nonEmptyQueue.size() > 1) {
emptyQueue.push(nonEmptyQueue.front());
nonEmptyQueue.pop();
}
// 返回并移除最后一个元素
int topElement = nonEmptyQueue.front();
nonEmptyQueue.pop();
return topElement;
}
int top() {
// 找到非空队列
queue<int>& nonEmptyQueue = q1.empty() ? q2 : q1;
queue<int>& emptyQueue = q1.empty() ? q1 : q2;
// 将非空队列中的元素移动到空队列,直到剩下最后一个元素
while (nonEmptyQueue.size() > 1) {
emptyQueue.push(nonEmptyQueue.front());
nonEmptyQueue.pop();
}
// 返回最后一个元素,但不移除
int topElement = nonEmptyQueue.front();
emptyQueue.push(topElement); // 将最后一个元素放回队列
nonEmptyQueue.pop();
return topElement;
}
bool empty() {
return q1.empty() && q2.empty();
}
};
javascript">class MyStack {
constructor() {
this.q1 = [];
this.q2 = [];
}
push(x) {
// 将新元素加入非空队列
if (this.q1.length > 0) {
this.q1.push(x);
} else {
this.q2.push(x);
}
}
pop() {
// 找到非空队列
let nonEmptyQueue = this.q1.length > 0 ? this.q1 : this.q2;
let emptyQueue = this.q1.length > 0 ? this.q2 : this.q1;
// 将非空队列中的元素移动到空队列,直到剩下最后一个元素
while (nonEmptyQueue.length > 1) {
emptyQueue.push(nonEmptyQueue.shift());
}
// 返回并移除最后一个元素
return nonEmptyQueue.shift();
}
top() {
// 找到非空队列
let nonEmptyQueue = this.q1.length > 0 ? this.q1 : this.q2;
let emptyQueue = this.q1.length > 0 ? this.q2 : this.q1;
// 将非空队列中的元素移动到空队列,直到剩下最后一个元素
while (nonEmptyQueue.length > 1) {
emptyQueue.push(nonEmptyQueue.shift());
}
// 返回最后一个元素,但不移除
let topElement = nonEmptyQueue[0];
emptyQueue.push(nonEmptyQueue.shift()); // 将最后一个元素放回队列
return topElement;
}
empty() {
return this.q1.length === 0 && this.q2.length === 0;
}
}