【模板】队列

题目描述

请你实现一个队列(queue),支持如下操作:

  • push(x):向队列中加入一个数 $x$。
  • pop():将队首弹出。如果此时队列为空,则不进行弹出操作,并输出 ERR_CANNOT_POP
  • query():输出队首元素。如果此时队列为空,则输出 ERR_CANNOT_QUERY
  • size():输出此时队列内元素个数。

输入格式

第一行,一个整数 $n$,表示操作的次数。

接下来 $n$ 行,每行表示一个操作。格式如下:

  • 1 x,表示将元素 x 加入队列。
  • 2,表示将队首弹出队列。
  • 3,表示查询队首。
  • 4,表示查询队列内元素个数。

输出格式

输出若干行,对于每个操作,按「题目描述」输出结果。

每条输出之间应当用空行隔开。

样例输入 #1

13
1 2
3
4
1 233
3
2
3
2
4
3
2
1 144
3

样例输出 #1

2
1
2
233
0
ERR_CANNOT_QUERY
ERR_CANNOT_POP
144

数组模拟队列

#include <bits/stdc++.h>
using namespace std; 
const int MAXN=100010;
int q[MAXN];
//队列从数组下标1开始 
int front=1,rear=0;
void push(int x){
    if(rear>=MAXN)
        cout<<"队满!"<<endl;
    q[++rear]=x;
} 
//出队 
void pop(){
    if(rear-front+1==0)
        cout<<"ERR_CANNOT_POP\n";
    else
        front++;
} 
//查询 
int query(){
    if(rear-front+1==0)
        return -1;
    return q[front];
}
int size(){
    return rear-front+1;
} 
int main(){
    int n,s,x;
    cin>>n;
    while(n--){
        cin>>s;
        if(s==1){
            cin>>x;
            push(x); 
        }else if(s==2){
            pop();
        }else if(s==3){     
            x=query();
            if(x==-1)
                cout<<"ERR_CANNOT_QUERY\n";
            else
                cout<<x<<endl;
        }else{      
            x=size();
            cout<<size()<<endl;
        }      
    }
    return 0;
}

STL

#include<bits/stdc++.h>
using namespace std;   
int n;
queue<int> q;
int main()
{
    cin >> n;
    for (int i = 1; i <= n; i++)
    {
        int op, x;
        cin >> op;
        if (op == 1) cin >> x, q.push(x);//加入
        else if (op == 2)
        {
            if (q.empty()) cout << "ERR_CANNOT_POP\n";//要判断是否为空,否则RE
            else q.pop();//如果不为空,弹出
        }
        else if (op == 3)
        {
            if (q.empty()) cout << "ERR_CANNOT_QUERY\n";//同上
            else cout << q.front() << endl;//输出第一个
        }
        else cout << q.size() << endl;//输出队列大小
    }
    return 0;//结束
}

vector 模拟队列

#include<bits/stdc++.h>
using namespace std;
struct Queue{
    private:
        vector<long long> a;
    public:
        void push(int x){
              a.push_back(x); 
        }
        void pop(){
            if(a.empty()){
                cout<<"ERR_CANNOT_POP"<<endl; 
                return;
            } 
            //删除队首元素 
            a.erase(a.begin());
        }
        void query(){
            if(a.empty()){
                cout<<"ERR_CANNOT_QUERY"<<endl; 
                return;
            } 
            cout<<a[0]<<endl;
        }
        void size(){
            cout<<a.size()<<endl;
        }
};
long long n,x,s;
int main(){
    Queue b;
    cin>>n; 
    for (int i = 0; i < n; i++) {
        cin>>s;
        if(s==1){
            cin>>x;
            b.push(x); 
        }
        if(s==2) b.pop();//2 弹出队首 
        if(s==3) b.query();//查询队首 
        if(s==4) b.size();//查看队列个数 
    }
}