模拟队列

 

 

 

 重点:队列是有队头指针hh和队尾指针tt,判断空的条件是如果hh>=tt,队列就为空。

栈只能从一个入口出入,栈底永远在0位置(这个位置不存元素)。但是队列是从队尾t a i l入队,从队头h e a d出队的。所以入队的过程其实会让队尾t a i l 沿着数组索引的增长方向增长,出队的过程则会让队头h e a d 沿着数组索引的增长方向增长。

在元素入队时,先把队尾指针t a i l 加1,然后再在其位置写入元素值。元素出队时,直接把队头的指针head加1即可。直到队头指针再次处于超过队尾指针的位置,模拟队列为空。(参考csdn模拟栈)

#include<iostream>

using namespace std;

int hh=0,tt=-1;//队尾和队头指针初始位置

const int N=1e5+10;

int q[N];

int main(){

int m;

cin>>m;

while(m--){

stirng s;

cin>>s;

if(s=="push"){

int x;

cin>>x;

q[++tt]=x;

}else if(s=="pop"){

hh++;

}else if(s=="query"){

cout<<q[hh]<<endl;

}else

if(hh>=tt){

cout<<"YES“”<<endl;

else 

cout<<"NO"<<endl;

}

}

return 0;

}

posted @ 2023-03-09 17:48  chenxinyue  阅读(35)  评论(0)    收藏  举报