题目
解释
- 队列的顺序是先进先出
- 使用两个指针来实现这一功能
- 插入元素相当于将尾指针向后推进
- 弹出元素相当于将首指针向后推进,这样先进来的数就可以先被弹出
代码段
标准模板
const int N = 1e5 + 10;
//在队尾插入元素,在队头弹出元素
int q[N], hh, tt = -1;
int x;
//插入
q[++tt] = x;
//弹出
hh++;
//判断是否为空
cout << hh <= tt ? "!empty" : "empty";
//取出队头元素
q[hh]
q[tt]
题解
#include<iostream>
using namespace std;
const int N=1e5+10;
int q[N],hh,tt=-1;
//双指针
int main()
{
int m;
cin>>m;
while(m--)
{
string op;
cin>>op;
int x;
if(op=="push")
{
cin>>x;
q[++tt]=x;
}
//插入元素相当于将尾指针向后推进
else if(op=="pop")hh++;
//弹出元素相当于将首指针向后推进,这样先进来的数就可以先被弹出
else if(op=="empty")cout<<(hh<=tt?"NO":"YES")<<endl;
//如果两指针相遇,则代表队列为空
else cout<<q[hh]<<endl;
}
return 0;
}