温馨提示×

如何使用c++ stack类实现表达式求值

c++
小樊
82
2024-09-25 08:38:17
栏目: 编程语言

使用C++的stack类可以实现表达式求值,具体步骤如下:

  1. 定义一个运算符优先级队列,用于存储运算符和操作数。

  2. 遍历表达式中的每个字符,如果是数字,则将其转换为整数并压入栈中。

  3. 如果字符是运算符,则将其与栈顶的运算符进行比较,如果优先级更高,则将其压入栈中;否则,将栈顶的运算符弹出并输出结果,然后将当前运算符压入栈中。

  4. 遍历完表达式后,栈中剩余的都是操作数,将它们依次弹出并输出结果即可。

下面是一个示例代码:

#include <iostream>
#include <stack>
#include <string>
#include <cctype>

using namespace std;

int getPriority(char op) {
    if (op == '+' || op == '-') {
        return 1;
    } else if (op == '*' || op == '/') {
        return 2;
    } else {
        return -1;
    }
}

int main() {
    string exp = "3+4*2/(1-5)";
    stack<int> stk;
    for (char c : exp) {
        if (isdigit(c)) {
            stk.push(c - '0');
        } else {
            int b = stk.top();
            stk.pop();
            int a = stk.top();
            stk.pop();
            switch (c) {
                case '+':
                    stk.push(a + b);
                    break;
                case '-':
                    stk.push(a - b);
                    break;
                case '*':
                    stk.push(a * b);
                    break;
                case '/':
                    stk.push(a / b);
                    break;
            }
        }
    }
    while (!stk.empty()) {
        cout << stk.top() << " ";
        stk.pop();
    }
    return 0;
}

输出结果为:-3 -2 4 -1

0