小张经常会在打饭排队的时候由于无聊而东张西望。今天他对隔壁的打饭队伍进行了详细观察。隔壁队伍每次到达一名同学,他就会记录下这个同学的名字,同时队伍的第一个同学打饭完成后会离开队伍。同时小张有时候想关注一下队首或队尾的同学是谁。
小张正在忙着排队打饭,请你帮助他完成这一件任务。
解题思路:
队列模拟即可,利用stl或者手写队列均可,坑点是可能会leave一个空队列,但是题里没告诉qwq,记得排除这个,否则喜提re或者wa
代码:
#include<iostream>
#include<queue>
using namespace std;
queue<string> q;
int main(){
int t;
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin>>t;
while(t--){
char c[11];
cin>>c;
if(c[0]=='A'){
string s;
cin>>s;
q.push(s);
}
else if(c[0]=='L'){
if(!q.empty())q.pop();
}
else if(c[8]=='d'){
if(!q.empty())cout<<q.front()<<endl;
else cout<<"Empty queue"<<endl;
}
else {
if(!q.empty())cout<<q.back()<<endl;
else cout<<"Empty queue"<<endl;
}
}
}
数组模拟版(当时忘判空了)
#include<iostream>
using namespace std;
string l[2000010];
int hh,tt=-1;
int idx;
int main(){
int t;
cin>>t;
while(t--){
char c[10];
cin>>c;
if(c[0]=='A'){
string s;
cin>>s;
l[++tt]=s;
}
else if(c[0]=='L'){
if(hh<=tt)hh++;
}
else if(c[8]=='d'){
if(hh<=tt)cout<<l[hh]<<endl;
else puts("Empty queue");
}
else {
if(hh<=tt)cout<<l[tt]<<endl;
else puts("Empty queue");
}
}
}