解决问题的思路:用两个队列实现栈。算法保证了两个队列至少有一个为空。
代码如下:
class Stack {
private:
queue<int> queue1;
queue<int> queue2;
public:
// Push element x onto stack.
void push(int x) {
if(queue1.empty() && queue2.empty()) {
queue1.push(x);
return;
}
if(!queue1.empty()) {
queue1.push(x);
return;
}
if(!queue2.empty()) {
queue2.push(x);
return;
}
}
// Removes the element on top of the stack.
void pop() {
if(!queue1.empty()) {
for(; queue1.size() > 1; ) {
queue2.push(queue1.front());
queue1.pop();
}
queue1.pop();
return;
}
if(!queue2.empty()) {
for(; queue2.size() > 1; ) {
queue1.push(queue2.front());
queue2.pop();
}
queue2.pop();
return;
}
}
// Get the top element.
int top() {
if(!queue1.empty()) {
for(; queue1.size() > 1; ) {
queue2.push(queue1.front());
queue1.pop();
}
int tmp = queue1.front();
queue1.pop();
queue2.push(tmp);
return tmp;
}
if(!queue2.empty()) {
for(; queue2.size() > 1; ) {
queue1.push(queue2.front());
queue2.pop();
}
int tmp = queue2.front();
queue2.pop();
queue1.push(tmp);
return tmp;
}
}
// Return whether the stack is empty.
bool empty() {
return queue1.empty() && queue2.empty();
}
};