题解 | #表达式求值# 双栈

表达式求值

https://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d

#include <iostream>
#include <string>
#include <stack>
#include <map>
using namespace std;

map<char, int> prioit = {
    {'+', 0},
    {'-', 0},
    {'*', 1},
    {'/', 1},
    {'(', -1},
    {')', 2}
};
bool compare(char& a, char& b) {
    if (prioit[a] < prioit[b]) return false;
    return true;
}

void myOperator(stack<int>& num, stack<char>& op) {
    int b = num.top();
    num.pop();
    int a = num.top();
    num.pop();
    char c = op.top();
    op.pop();

    int res;
    switch (c) {
        case '+':
            res =  a + b;
            break;
        case '-':
            res = a - b;
            break;
        case '*':
            res = a * b;
            break;
        case '/':
            res = a / b;
            break;
    }
    num.push(res);
}

int main() {
    string s;
    cin >> s;
    s = s + ")";
    stack<int> num;
    stack<char> op;
    op.push('(');
    string n = "";
    char pre = '(';
    for (char& i : s) {
        if (prioit.count(i) == 0) {
            n += i;
        } else {
            if (i == '-') {
                if (prioit.count(pre) != 0 && pre != ')') {
                    num.push(0);
                }
            }

            if (n.size() != 0) {
                int num_ = stoi(n);
                num.push(num_);
                n = "";
            }
            if (i == '(') {
                op.push(i);
            } else if (i == ')') {
                while (op.top() != '(') {
                    myOperator(num, op);
                }
                op.pop();
            } else {
                while (compare(op.top(), i)) {
                    myOperator(num, op);
                }
                op.push(i);
            }
        }
        pre = i;
    }

    cout << num.top();
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务