简单的个位后缀表达式实现——栈的应用

来源:互联网 发布:人肉搜索网络团队 骗 编辑:程序博客网 时间:2024/05/29 14:35
#include <iostream>#include <vector>#include <stack>using namespace std;int compare(char ch1,char ch2){    switch(ch1){        case '+':        case '-':if(ch2=='*'||ch2=='/')                    return 1;                else                    return 0;                break;        case '*':        case '/':return 0;break;    }}int main(){    vector <char>num;    stack <char>ope;    stack <int>cal;    char a;    while(cin>>a&&a!='='){        if(a>='0'&&a<='9'){            num.push_back(a);        }        else{            if(!ope.empty()){                while(!ope.empty()&&compare(a,ope.top())){                    num.push_back(ope.top());                    ope.pop();                }                ope.push(a);            }            else                ope.push(a);        }    }    while(!ope.empty()){        num.push_back(ope.top());        ope.pop();    }    for(auto ch:num)        cout<<ch<<' ';        cout<<endl;    int sum=0;    for(auto d:num){        if(d>='0'&&d<='9'){            cal.push(d-'0');        }        else{            int a=cal.top();            cal.pop();            int b=cal.top();            cal.pop();            switch(d){            case '+':sum=a+b;                    cal.push(sum);break;            case '-':sum=b-a;                    cal.push(sum);break;            case '*':sum=a*b;                    cal.push(sum);break;            case '/':sum=b/a;                    cal.push(sum);break;            }        }    }    cout<<sum<<endl;    return 0;}

0 0