PAT堆栈模拟队列

来源:互联网 发布:编程判断字母大小写 编辑:程序博客网 时间:2024/05/22 04:36
使用堆栈模拟队列,相当于当用两个桶装水:
一:为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;}


0 0