实现一个队列,队列初始为空,支持四种操作:
-
push x
– 向队尾插入一个数 x;
-
pop
– 从队头弹出一个数;
-
empty
– 判断队列是否为空;
-
query
– 查询队头元素。
/*
数组模拟队列
队列:先进先出
*/
#include <iostream>
using namespace std;
const int N = 1e5 + 10;
// hh:队头,tt:队尾
int q[N], hh, tt;
// 初始化
void init()
{
hh = 0;
tt = -1;
}
// 插入到队尾
void push(int x)
{
q[++tt] = x;
}
// 弹出队头
void pop()
{
// hh在左边,tt在右边
hh++;
}
// 判断队列是否为空
bool IsEmpty()
{
if(hh <= tt) return false; // 非空
else return true; // 空
}
// 取出队头的元素
void query(int &x)
{
x = q[hh];
}
int main()
{
init();
int m;
cin >> m;
while(m--)
{
string op;
int x, k;
cin >> op;
if(op == "push")
{
cin >> x;
push(x);
}
else if(op == "pop")
{
if(!IsEmpty()) pop();
}
else if(op == "empty")
{
if(IsEmpty()) cout << "YES" << endl;
else cout << "NO" << endl;
}
else if(op == "query")
{
if(!IsEmpty())
{
query(k);
cout << k << endl;
}
}
}
return 0;
}