两个队列实现栈(面试C++)
实现如下:
class MyStack {
private:
std::queue<int> queue1;
std::queue<int> queue2;
public:
void push(int x) {
if (queue1.empty()) {
queue2.push(x);
}
else {
queue1.push(x);
}
}
int pop() {
if (empty()) {
throw std::runtime_error("Stack is empty");
}
int top_element;
if (queue1.empty()) {
while (queue2.size() > 1) {
queue1.push(queue2.front());
queue2.pop();
}
top_element = queue2.front();
queue2.pop();
}
else {
while (queue1.size() > 1) {
queue2.push(queue1.front());
queue1.pop();
}
top_element = queue1.front();
queue1.pop();
}
return top_element;
}
int top() {
if (empty()) {
throw std::runtime_error("Stack is empty");
}
int top_element;
if (queue1.empty()) {
top_element = queue2.back();
}
else {
top_element = queue1.back();
}
return top_element;
}
bool empty() {
return queue1.empty() && queue2.empty();
}
};