题目链接:堆栈模拟队列
题目大意:要求用两个堆栈来模拟一个队列的操作,队列是先进先出,堆栈是先进后出,因此,我们需要两个堆栈来完成这个转换,一个堆栈输出,一个堆栈输入做一个缓冲作用。
核心方法: 找到一个容量最小的堆栈(栈1)来做缓冲堆栈(因为后面需要把这里的数据放入另一个堆栈(栈2),确保转换的时候不会爆栈)
分情况讨论:
1.当c = 'A’时
如果栈1满,栈2不为空, : 输出:ERROR:Full
如果栈1满,栈2为空 :把栈1的所有元素都放入栈2,并且把刚输入的元素存入栈1
栈1没满 : 把刚输入的元素存入栈1
2.当c = 'D’时
如果栈2不为空 : 输出栈顶元素
如果栈2为空,栈1不为空 : 把栈1的所有元素都放入栈2,输出栈顶元素,并删除它
如果栈2为空,栈1为空,输出 : ERROR:Empty
代码如下:
#include<iostream>
#include<stack>
using namespace std;
stack<int> stk1,stk2;
int n,m,x;
char c;
int main(){
cin >> n >> m;
getchar();
int t1 = min(n,m);
while(1){
cin >> c;
if(c == 'T') break;
if(c == 'A'){
cin >> x;
if(stk1.size() == t1 && stk2.size() > 0){
cout<<"ERROR:Full\n";
}
else if(stk1.size() == t1){
while(stk1.size()){
int t = stk1.top();
stk2.push(t);
stk1.pop();
}
stk1.push(x);
}
else stk1.push(x);
}else if(c == 'D'){
if(stk2.size() > 0){
cout<<stk2.top()<<endl;
stk2.pop();
}else if(stk2.size() == 0 && stk1.size() > 0){
while(stk1.size()){
int t = stk1.top();
stk2.push(t);
stk1.pop();
}
cout<<stk2.top()<<endl;
stk2.pop();
}else{
cout<<"ERROR:Empty\n";
}
}
}
return 0;
}