模拟队列
队列特征:先进先出
模拟方式:
定义两个指针表示队头和队尾:head,tail
插入:队尾插入 x,queue[tail++] = x
弹出:队头弹出:head++
判断空:head == tail
访问队首元素:queue[head]
上述操作建立在初始化:head = 0, tail = 0
的基础上
当初始化为:head = 0, tail = -1
时,在插入和判断空的操作上有些许不同:
插入:queue[++tail]
判空:head > tail
例题
#include <iostream>
#include <string>
using namespace std;
const int N = 1e5 + 5;
int queue[N], head, tail;
int main()
{
string op;
int T, x;
cin >> T;
while(T--)
{
cin >> op;
if(op == "push")
{
cin >> x;
queue[tail++] = x;
}
else if(op == "pop")
{
head++;
}
else if(op == "empty")
{
cout << (head == tail ? "YES" : "NO") << endl;
}
else
{
cout << queue[head] << endl;
}
}
return 0;
}