题目描述
实现一个队列,队列初始为空,支持四种操作:
(1) “push x” – 向队尾插入一个数x;
(2) “pop” – 从队头弹出一个数;
(3) “empty” – 判断队列是否为空;
(4) “query” – 查询队头元素。
输入样例
10
push 6
empty
query
pop
empty
push 3
push 4
pop
query
push 6
输出样例
NO
6
YES
4
思路
- 数组模拟队列,队头hh = 0, 队尾 tt = -1 数从队尾进队头出去
- 入队 q[ tt] = x, 出对 hh , 判断是否为空 hh <= tt , q[hh]就是队头元素
#include<iostream>
using namespace std;
const int N = 1000010;
int m;
int q[N], hh, tt = -1;
int main(){
cin >> m;
while(m --){
string op;
int x;
cin >> op;
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;
}