题目描述
实现一个队列,队列初始为空,支持四种操作:
1.push x – 向队尾插入一个数 x;
2.pop – 从队头弹出一个数;
3.empty – 判断队列是否为空;
4.query – 查询队头元素。
现在要对队列进行M个操作,其中的每个操作3和操作4都要输出相应的结果。
样例
输入样例:
10
push 6
empty
query
pop
empty
push 3
push 4
pop
query
push 6
输出样例:
NO
6
YES
4
C++ 代码
#include <iostream>
#include <cstring>
using namespace std;
#define Max 100010
struct queue{
int arr[Max];
int head;
int tail;
};
void init(struct queue* q){
q->head = 0;
q->tail = 0;
}
bool pop(struct queue* q,int* x){
if(q->head == q->tail) return false;
else{
(*x) = q->arr[q->head];
q->head = (q->head+1)%Max;
}
return true;
}
bool push(struct queue* q,int x){
if((q->tail+1)%Max == q->head) return false;
else{
q->arr[q->tail] = x;
q->tail = (q->tail+1)%Max;
}
return true;
}
bool empty(struct queue* q){
if(q->head == q->tail){
cout<<"YES"<<endl;
return true;
}
else{
cout<<"NO"<<endl;
return false;
}
}
bool query(struct queue* q,int* x){
if(q->head == q->tail) return false;
else{
(*x) = q->arr[q->head];
}
return true;
}
int main(){
struct queue q;
init(&q);
int num;
cin>>num;
int x;
while(num--){
string str;
cin>>str;
if(str == "push"){
int k;
cin>>k;
push(&q,k);
}
else if(str == "pop"){
pop(&q,&x);
}
else if(str == "empty"){
empty(&q);
}
else{
query(&q,&x);
cout<<x<<endl;
}
}
return 0;
}