中缀表达式求值

Posted on 2023-02-25 22:19  lyc2002  阅读(18)  评论(0编辑  收藏  举报
#include <cstdio>
#include <cstring>
#include <stack>
#include <unordered_map>

using namespace std;

const int N = 100010;

char str[N];
stack<int> num;
stack<char> op;
unordered_map<char, int> pr({{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}});

void eval()
{
    int b = num.top(); num.pop();
    int a = num.top(); num.pop();
    char c = op.top(); op.pop();
    int x = 0;
    if (c == '+') x = a + b;
    else if (c == '-') x = a - b;
    else if (c == '*') x = a * b;
    else x = a / b;
    num.push(x);
}

int main()
{
    scanf("%s", str);
    
    for (int i = 0; i < strlen(str); i++) {
        char c = str[i];
        if (c == '(') op.push(c);
        else if (c == ')') {
            while (op.top() != '(') eval();
            op.pop();
        } else if (isdigit(c)) {
            int x = 0, j = i;
            while (j < strlen(str) && isdigit(str[j])) x = x * 10 + str[j++] - '0';
            i = j - 1;
            num.push(x);
        } else {
            while (op.size() && op.top() != '(' && pr[op.top()] >= pr[c]) eval();
            op.push(c);
        }
    }
    
    while (op.size()) eval();
    
    printf("%d", num.top());
    
    return 0;
}