表达式求值(栈)

https://www.acwing.com/solution/content/40978/

#include<unordered_map>
#include<iostream>
#include<stack>
#include<string>
using namespace std;
stack<int> num;//double stack,this is number stack
stack<char> op;//this is operator stack
unordered_map<char, int> h{{'+',1},{'-',1},{'*',2},{'/',2}};
//unordered_map存运算符优先级
void eval(){
    int a=num.top();//second number
    num.pop();
    int b=num.top();//first number
    num.pop();
    int p=op.top();//operator
    op.pop();
    int res=0;
    if(p=='+')
        res=b+a;
    else if(p=='-')
        res=b-a;
    else if(p=='*')
        res=b*a;
    else if(p=='/')
        res=b/a;
    
    num.push(res);//push res num stack
}
int main(){
    string a;
    cin>>a;
    for(int i=0;i<a.size();i++)
    {
        if(isdigit(a[i])){//if a[i] is number
            int x=0,j=i;
            //change char number to int number
            while(isdigit(a[j])){//防止越界
                x=x*10+a[j]-'0';
                j++;
            }
            num.push(x);//push number in num stack
            i=j-1;//index become j-1
        }
        else if(a[i]=='(')//'('无优先级,直接入栈
            op.push(a[i]);
        else if(a[i]==')')
        {
            while(op.top()!='(')//一直计算到左括号
                eval();
            op.pop();//左括号出栈
        }
        else{
            while(op.size()&&h[op.top()]>=h[a[i]])
            //即将入栈的运算符优先级小于栈顶运算符
            //则先计算
                eval();
            op.push(a[i]);//再入栈
        }
    }
    while(op.size()) eval();//计算剩余的优先级较低的运算
    cout<<num.top()<<endl;
    return 0;
}
posted @ 2022-04-18 16:53  zzq12138  阅读(27)  评论(0)    收藏  举报