题解 | 【模板】队列
【模板】队列
https://www.nowcoder.com/practice/afe812c80ad946f4b292a26dd13ba549
#include <iostream>
#include <bits/stdc++.h>
#include <string>
using namespace std;
class QueueWithStacks {
private:
stack<int> st1; // 输入栈
stack<int> st2; // 输出栈
// 辅助函数:当输出栈为空时,将输入栈数据转移过来
void move_st1_to_st2() {
while (!st1.empty()) {
st2.push(st1.top());
st1.pop();
}
}
public:
// 入队操作
void push(int num) {
st1.push(num);
}
// 获取队首元素
void front() {
if (st1.empty() && st2.empty()) {
cout << "error" << endl;
return;
}
if (st2.empty()) {
move_st1_to_st2();
}
cout << st2.top() << endl;
}
// 出队操作
void pop() {
if (st1.empty() && st2.empty()) {
cout << "error" << endl;
return;
}
if (st2.empty()) {
move_st1_to_st2();
}
cout << st2.top() << endl;
st2.pop();
}
};
int main() {
int n;
cin >> n;
QueueWithStacks queue; // 创建队列对象
for (int i = 0; i < n; ++i) {
string cmd;
cin >> cmd;
if (cmd == "push") {
int num;
cin >> num;
queue.push(num);
}
else if (cmd == "front") {
queue.front();
}
else if (cmd == "pop") {
queue.pop();
}
}
return 0;
}
// 64 位输出请用 printf("%lld")
使用双栈实现队列,模拟先进先出,push压入栈1,front和pop,将栈1的数据迁移到栈2

