栈模拟队列需要两个,而队列模拟栈最少只需要一个。即每次需要出栈时,把队尾元素返回即可(其他元素出队再入队)。
下面给出用双队列模拟栈的代码,其中now
标记的使用,比较巧妙
class MyStack {
private:
queue<int> qArr[2];
int now=0;
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
qArr[1-now].push(x);
while(!qArr[now].empty()){
qArr[1-now].push(qArr[now].front());
qArr[now].pop();
}
now=1-now;
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int ans=qArr[now].front();
qArr[now].pop();
return ans;
}
/** Get the top element. */
int top() {
return qArr[now].front();
}
/** Returns whether the stack is empty. */
bool empty() {
return qArr[now].empty();
}
};