主要思路和注意点
用两个栈实现队列,主要注意点有两个:
1.从push栈向pop栈转移时一定要一次全部转移过去。
2.在pop栈不空时不能转移。
代码和测试
#include <bits/stdc++.h>
using namespace std;
class TwoStacksQueue{
private:
stack<int> stackPush;
stack<int> stackPop;
void pushToPop(){
if(stackPop.empty()){
while(!stackPush.empty()){
int temp=stackPush.top();
stackPush.pop();//这个函数没有返回值,和vector.pop_back一样
stackPop.push(temp);
}
}
}
public:
void add(int pushInt){
stackPush.push(pushInt);
pushToPop();
}
int poll(){
if(stackPop.empty()&&stackPush.empty()){
throw "Queue is empty!";
}
pushToPop();
int res=stackPop.top();
stackPop.pop();
return res;
}
int top(){
if(stackPop.empty()&&stackPush.empty()){
throw "Queue is empty!";
}
pushToPop();
return stackPop.top();
}
};
int main(){
TwoStacksQueue two;
int array[3]={1,2,3};
two.add(array[0]);
two.add(array[1]);//这里因为Pop队列不空,所以不会把后面两个数放进去
two.add(array[2]);
cout<<two.top()<<endl;
cout<<two.poll()<<endl;
try{
cout<<two.top()<<endl;
}catch(const char* msg){
cerr << msg << endl;
}
cout<<two.poll()<<endl;
cout<<two.top()<<endl;
cout<<two.poll()<<endl;
return 0;
}