写过队列的强化训练 5都会,不会的看过来
2026-10-05 19:03:00
发布于:广东
7阅读
0回复
0点赞
也是非常的简单
首先,肯定要初始化啦
#include<bits/stdc++.h>
using namespace std;
int n;
queue<int>q;
初始化完,就是主函数及输入
int main(){
cin>>n;
由于要求输入 n 条指令,所以说写循环输入
while(n--){
int o;
cin>>o;
这里用 for 循环也是可以的
接着,就是判断指令的内容了
咱们先把各个指令的操作列个表
| 1 | 2 | 3 |
|---|---|---|
| 入队 | 出队 | 访问队首 |
接着,就开始写指令1的内容了
指令1要求入队x,所以先定义x,再入队
if(o==1){
int x;
cin>>x;
q.push(x);
}
然后写指令2的内容
指令2要求出队队首,但是要注意:
题目要求,如果为空则输出impossible!
else if(o==2){
if(q.empty()) cout<<"impossible!\n";
else q.pop();
}
再接着,写指令3的内容
指令3要求输出队首,但是要注意:
题目要求,如果为空则也要输出impossible!
else if(o==3){
if(q.empty()) cout<<"impossible!\n";
else cout<<q.front()<<endl;
}
最后,对不合法的指令输出impossible!
else cout<<"impossible!\n";
结束
}
return 0;
}
——————————————————————————————————————————————————————————
一下为完整代码
#include<bits/stdc++.h>
using namespace std;
int n;
queue<int>q;
int main(){
cin>>n;
while(n--){
int o;
cin>>o;
if(o==1){
int x;
cin>>x;
q.push(x);
}else if(o==2){
if(q.empty()) cout<<"impossible!\n";
else q.pop();
}else if(o==3){
if(q.empty()) cout<<"impossible!\n";
else cout<<q.front()<<endl;
}else cout<<"impossible!\n";
}
return 0;
}
——————————————————————————————————————————————————————————
点个赞吧,求求了,这真的花了我好大心血/(ㄒoㄒ)/~~
这里空空如也

有帮助,赞一个