
二. 理论
- 队列(queue)是一种具有「先进入队列的元素一定先出队列」性质的表。由于该性质,队列通常也被称为先进先出(first in first out)表,简称 FIFO 表。
三. 代码
#include<iostream>
#include<cstdio>
using namespace std;
const int N=1e5+10;
namespace Question
{
int m;
}
using namespace Question;
namespace Queue
{
int q[N], hh, tt;//数组模拟队列,hh是队头, tt为队尾
void init()//初始化操作, 清空队列
{
hh=0, tt=-1;
}
void push(int x)//队尾插入一个数
{
q[++tt]=x;
}
void pop()//队头弹出一个数
{
hh++;
}
bool isEmpty()//判断队列是否为空
{
return hh>tt;
}
int queryHead()//查询队头元素
{
return q[hh];
}
}
using namespace Queue;
signed main()
{
cin>>m;
init();
while(m--)
{
int x;
char op[9];//操作
scanf("%s", op);
if(*op=='p'&&op[1]=='u')
{
scanf("%d", &x);
push(x);
}
else if(op[1]=='o') pop();
else if(*op=='e')
{
if(isEmpty()) puts("YES");
else puts("NO");
}
else if(*op=='q') printf("%d\n", queryHead());
}
}
四. cppSTL中的队列
- STL 中的 queue 容器提供了一众成员函数以供调用。其中较为常用的有:
- 声明:queue<> q
- 返回队首元素:q.front()
- 返回队尾元素:q.back()
- 在队尾插入元素:q.push()
- 弹出队首元素:q.pop()
- 队列是否为空:q.empty()
- 返回队列中元素的数量:q.size()
- 赋值:=