思路:
用两个队列互相导来实现一个栈。
c++ code:
class Stack {
private:
int cur = 0;
queue<int> q[2];
public:
// Push element x onto stack.
void push(int x) {
q[cur].push(x);
}
// Removes the element on top of the stack.
void pop() {
while(q[cur].size() > 1) {
q[1 - cur].push(q[cur].front());
q[cur].pop();
}
q[cur].pop();
cur = 1 - cur;
}
// Get the top element.
int top() {
while(q[cur].size() > 1) {
q[1 - cur].push(q[cur].front());
q[cur].pop();
}
int v = q[cur].front();
q[1-cur].push(q[cur].front());
q[cur].pop();
cur = 1 - cur;
return v;
}
// Return whether the stack is empty.
bool empty() {
return q[cur].empty();
}
};