需要实现队列的push,pop以及查询队列头部的功能
思路:
首先定义两个栈,s1,s2,s1用来存储元素,s2用来实现队列;对于push功能,如果s2为空,则加入s2一个元素,其余加入s1,否则都加入s1(此时s1是倒序的队列);
对于pop功能,先判断s2是否为空,如果为空,则将s1中的元素全部加入s2,此时s2即为队列的顺序,同理,不为空则不进行操作;然后删去s2的头部即可,同理,查询功能也是s2.top()即可。
代码
#include<bits/stdc++.h>
using namespace std;
int n,x;
string s;
int main()
{
cin >> n;
stack<int> s1,s2;
while(n--)
{
cin >> s;
if(s == "add")//添加
{
cin >> x;
s1.push(x);
if(s2.empty())
{
while(!s1.empty()){
int t = s1.top();
s1.pop();
s2.push(t);
}
}
}
else if(s == "poll"){//删除
if(s2.empty()&&!s1.empty()){
while(!s1.empty()){
int t = s1.top();
s1.pop();
s2.push(t);
}
}
s2.pop();
}
else{//查询
if(s2.empty()&&!s1.empty()){
while(!s1.empty()){
int t = s1.top();
s1.pop();
s2.push(t);
}
}
cout << s2.top() << endl;
}
}
}