您的位置:首页 > 其它

PAT堆栈模拟队列

2016-07-12 08:58 211 查看
使用堆栈模拟队列,相当于当用两个桶装水:

一:为A 装水的时候

当左边的水桶满了,而右边的不为空的话,就可以说不能倒水了,输出Full

当左边的水桶没满,就可以倒到它满为止

当左边的水桶满了,右边的没有水,就把所有的水倒到右边去

二:倒水的时候

当右边的水桶满了之后就可以倒

如果是空的重新从左边装水

如果左边也没有水,

那么说明是空的,输出Empty

#include <iostream>
#include <cstring>
#include <cstdio>
#include <stack>
using namespace std;
stack<int>a1;
stack<int>a2;
int main(){
int n1,n2;
cin>>n1>>n2;
if(n1 > n2){
swap(n1,n2);
}
int dex;
char c;
while(cin>>c && c != 'T'){
if(c == 'A'){
cin>>dex;
if(a1.size() == n1 &&a2.size() != 0){
cout<<"ERROR:Full"<<endl;
continue;
}
if(a1.size() != n1){
a1.push(dex);
}else{
while(a1.size() != 0){
a2.push(a1.top());
a1.pop();
}
a1.push(dex);
}
}
if(c == 'D'){
if(a2.size() == 0 && a1.size() == 0){
cout<<"ERROR:Empty"<<endl;
continue;
}
if(a2.size()== 0 && a1.size() != 0){
while(a1.size() != 0){
a2.push(a1.top());
a1.pop();
}
cout<<a2.top()<<endl;
a2.pop();
}else{
cout<<a2.top()<<endl;
a2.pop();
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  PAT