栈实现表达式求值

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stack>

using namespace std;

int yunsuan(int a, int b, char op){
    int res;
    if (op == '-')
        res = a - b;
    if (op == '+')
        res = a +b;
    if (op == '*')
        res = a * b;
    if (op == '/')
        res = a / b;
    return res;
}

int judge (char tmp){
    if (tmp == ' ')
        return -1;
    if (tmp >= '0' && tmp <= '9') {
        return 0;
    }
    else if (tmp == '=')
        return 1;
    else if (tmp == '-' || tmp == '+')
        return 2;
    else if (tmp == '*' || tmp == '/')
        return 3;
    else if (tmp == '(')
        return -2;
    else if (tmp == ')')
        return 4;
}

int main(){
    char shizi[100];
    stack <int> a;
    stack <char> b;
    while (~scanf("%s", shizi)){
        int len = strlen(shizi);

        for (int i = 0; i < len; i++){
          
            if (judge(shizi[i]) == 0)
                a.push(shizi[i] - '0');
            if (judge(shizi[i]) == 1) {
                while (b.empty() != 1) {
                    int t1 = a.top();
                    a.pop();
                    int t2 = a.top();
                    a.pop();
                    a.push(yunsuan(t1, t2, b.top()));
                    b.pop();
                }
            }
            if (judge(shizi[i]) == 2) {
                while (b.empty() != 1 && judge(b.top()) >= 2){
                    int t1 = a.top();
                    a.pop();
                    int t2 = a.top();
                    a.pop();
                    a.push(yunsuan(t1, t2, b.top()));
                    b.pop();
                }
                b.push(shizi[i]);
            }
            if (judge(shizi[i]) == 3) {
                while (b.empty() != 1 && judge(b.top()) >= 3){
                    int t1 = a.top();
                    a.pop();
                    int t2 = a.top();
                    a.pop();
                    a.push(yunsuan(t1, t2, b.top()));
                    b.pop();
                }
                b.push(shizi[i]);
            }

            if (judge(shizi[i])== -2)
                b.push(shizi[i]);

            if (judge(shizi[i]) == 4){

                while (b.empty() != 1 && b.top() != '(') {
                    int t1 = a.top();
                    a.pop();
                    int t2 = a.top();
                    a.pop();
                    a.push(yunsuan(t1, t2, b.top()));
                    b.pop();
                }
                b.pop();
            }
        }
        printf("%d\n", a.top());
        a.pop();

    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值