用两个栈实现队列c++
时间: 2023-12-24 19:04:12 浏览: 88
可以使用一个栈作为输入栈,另一个栈作为输出栈,实现队列的先进先出操作。具体实现如下:
```c++
class MyQueue {
private:
stack<int> inStack;
stack<int> outStack;
public:
void push(int x) {
inStack.push(x);
}
int pop() {
if (outStack.empty()) {
while (!inStack.empty()) {
outStack.push(inStack.top());
inStack.pop();
}
}
int res = outStack.top();
outStack.pop();
return res;
}
int peek() {
if (outStack.empty()) {
while (!inStack.empty()) {
outStack.push(inStack.top());
inStack.pop();
}
}
return outStack.top();
}
bool empty() {
return inStack.empty() && outStack.empty();
}
};
```
阅读全文