EOJ_1024_表达式

#include <bits/stdc++.h>

using namespace std;
//此方法与视频中的方法不太一致,不是先转化成后缀表达式后再计算
//而是边转换边计算
//先转换再计算缺点:会导致储存后缀表达式的stack内部数字无法辨别是符号还是计算出的结果
//需要另外设计
stack<int> res;
stack<char> sign;
int table[130]={0};//优先级

void init(int table[])
{
    table['-']=1;
    table['+']=1;
    table['*']=2;
    table['/']=2;
    table['(']=0;
    table[')']=0;
}
//这里要注意是&
void cal(stack<int> &res, char sign)
{
    int tmp2 = res.top();
    res.pop();
    int tmp1 = res.top();
    res.pop();
    if(sign=='-') res.push(tmp1-tmp2);
    if(sign=='+') res.push(tmp1+tmp2);
    if(sign=='*') res.push(tmp1*tmp2);
    if(sign=='/') res.push(tmp1/tmp2);
}

int main()
{
    init(table);
    string s;
    cin>>s;
    int len=s.size();
    int i=0;
    //因为循环中涉及到i的++,所以不用for
    while(i<len){
        if(isdigit(s[i])){
            int tmp=0;
            while(i<len &&isdigit(s[i])){
                tmp = tmp*10+s[i]-'0';
                i++;
            }
            res.push(tmp);
        }
        else{
            if(s[i]=='-'){
                if(i==0 ||s[i-1]=='('){
                    int tmp=0;
                    i++;
                    while(i<len &&isdigit(s[i])){
                        tmp = tmp*10+s[i]-'0';
                        i++;
                    }
                    res.push(-1*tmp);
                }
                else{
                    while(!sign.empty() &&table[s[i]]<=table[sign.top()]){
                        cal(res, sign.top());
                        sign.pop();
                    }
                    sign.push(s[i]);
                    i++;
                }
            }
            else{
                if(s[i]=='(') sign.push('(');
                else if(s[i]==')'){
                    while(sign.top()!='('){
                        cal(res, sign.top());
                        sign.pop();
                    }
                    sign.pop();
                }
                else{
                    while(!sign.empty() &&table[s[i]]<=table[sign.top()]){
                        cal(res, sign.top());
                        sign.pop();
                    }
                    sign.push(s[i]);
                }
                i++;
            }
        }
    }
    while(!sign.empty()){
        cal(res, sign.top());
        sign.pop();
    }
    cout<<res.top()<<endl;

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值