队列 - OI Wiki:一种头部出队,尾部入队的数据结构
flowchart LR
队首-->2-->3--...-->6-->7-->队尾
C++实现代码#
#include<iostream>
using namespace std;
const int ARR_SIZE=1000001;
struct queue
{
int q[ARR_SIZE];
int l=1,r=0;
bool empty()
{
return l>r;
}
void push (int x)
{
q[++r]=x;
}
void pop ()
{
++l;
}
int front()
{
return q[l];
}
int back()
{
return q[r];
}
int size()
{
return r-l+1;
}
void clean()
{
l=1;r=0;
}
};
int main() {
queue q;
int n;
scanf("%d", &n);
while (n--) {
int opt;
scanf("%d", &opt);
if (opt == 1)
{
int x;
scanf("%d", &x);
q.push(x);
}
else if (opt == 2)
{
if (q.empty())
printf("ERR_CANNOT_POP\n");
else
q.pop();
}
else if (opt == 3)
{
if (q.empty()) printf("ERR_CANNOT_QUERY\n");
else printf("%d\n", q.front());
}
else printf("%d\n", q.size());
}
return 0;
}
STL队列#
定义头文件:#include<queue>
设置变量:queue<int> q
使用函数:
- 元素访问
q.front()返回队首元素q.back()返回队尾元素
- 修改
q.push()在队尾插入元素q.pop()弹出队首元素
- 容量
q.empty()队列是否为空q.size()返回队列中元素的数量
