【题目来源】
https://www.luogu.com.cn/problem/B3616
【题目描述】
请你实现一个队列(queue),支持如下操作:
● push(x):向队列中加入一个数 x。
● pop():将队首弹出。如果此时队列为空,则不进行弹出操作,并输出 ERR_CANNOT_POP。
● query():输出队首元素。如果此时队列为空,则输出 ERR_CANNOT_QUERY。
● size():输出此时队列内元素个数。
【输入格式】
第一行,一个整数 n,表示操作的次数。
接下来 n 行,每行表示一个操作。格式如下:
● 1 x,表示将元素 x 加入队列。
● 2,表示将队首弹出队列。
● 3,表示查询队首。
● 4,表示查询队列内元素个数。
【输出格式】
输出若干行,对于每个操作,按「题目描述」输出结果。
每条输出之间应当用空行隔开。
【输入样例】
13
1 2
3
4
1 233
3
2
3
2
4
3
2
1 144
3
【输出样例】
2
1
2
233
0
ERR_CANNOT_QUERY
ERR_CANNOT_POP
144
【算法分析】
模拟队列代码:https://blog.csdn.net/hnjzsyjyj/article/details/133636109
【算法代码】
#include <bits/stdc++.h>
using namespace std;
int main() {
queue<int> q;
int n;
cin>>n;
while(n--) {
int op,x;
cin>>op;
if(op==1) cin>>x, q.push(x);
else if(op==2) {
if(q.empty()) cout<<"ERR_CANNOT_POP"<<endl;
else q.pop();
} else if(op==3) {
if(q.empty()) cout<<"ERR_CANNOT_QUERY"<<endl;
else cout<<q.front()<<endl;
} else cout<<q.size()<<endl;
}
return 0;
}
/*
in:
13
1 2
3
4
1 233
3
2
3
2
4
3
2
1 144
3
out:
2
1
2
233
0
ERR_CANNOT_QUERY
ERR_CANNOT_POP
144
*/
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/133636109
https://blog.csdn.net/hnjzsyjyj/article/details/144043154
https://blog.csdn.net/hnjzsyjyj/article/details/144042212