表达式求值(算法题)
#include <bits/stdc++.h> // 引入常用头文件
using namespace std;stack<int> num; // 存储操作数的栈
stack<char> op; // 存储运算符的栈/* 执行一次运算操作:1. 从num栈弹出两个操作数(n2先弹出,作为右操作数)2. 从op栈弹出运算符3. 根据运算符计算结果,将结果压回num栈
*/
void eval()
{// 弹出右操作数(因为栈是后进先出)int n2 = num.top(); num.pop(); // 弹出左操作数int n1 = num.top(); num.pop(); // 弹出当前运算符char oper = op.top(); op.pop(); int res;switch(oper) { // 根据运算符计算结果case '+': res = n1 + n2; break;case '-': res = n1 - n2; break;case '*': res = n1 * n2; break;case '/': res = n1 / n2; break;}num.push(res); // 将结果压回操作数栈
}int main()
{string expr;cin >> expr; // 读取表达式字符串// 定义运算符优先级表,左括号未定义因为需要特殊处理unordered_map<char, int> priority{{'+',1}, {'-',1}, {'*',2}, {'/',2}};for (int i = 0; i < expr.size(); i++) { // 遍历每个字符char c = expr[i];if (isdigit(c)) { // 处理数字字符int value = 0;int j = i;// 连续读取完整数字(处理多位数的情形)while (j < expr.size() && isdigit(expr[j])) {value = value * 10 + (expr[j++] - '0');}i = j - 1; // 更新i到最后一个数字的位置(因为循环会i++)num.push(value); // 数字压栈/* 模拟过程示例:输入"12+34",当i=0时识别到数字,得到j=2,value=12,将i更新为1,循环继续处理位置2的'+'*/}else if (c == '(') { // 左括号直接入栈op.push(c);}else if (c == ')') { // 右括号:计算直到遇到左括号// 不断执行运算,直到栈顶出现左括号while (op.top() != '(') {eval();}op.pop(); // 弹出左括号/* 模拟示例:处理表达式 "(3+5 * 2)" 时,遇到右括号,运算栈中的 '*' 和 '+' 将依次被处理,保留计算结果在num栈中*/}else { // 处理普通运算符(+-*/)/* 优先级处理:当前运算符优先级 <= 栈顶运算符优先级时,先执行栈顶运算,保证运算顺序正确例如:当前是'+',栈顶是'*'时,先计算乘法*/while (op.size() && op.top() != '(' && priority[c] <= priority[op.top()]) {eval();}op.push(c); // 当前运算符入栈}}// 处理剩余的所有运算符while (op.size()) {eval();}cout << num.top() << endl; // 输出最终结果return 0;
}/*
示例表达式处理模拟1:3+5 * 2
1. '3'压入num → num:[3]
2. '+' 入栈 → op:[+]
3. '5'压入num → num:[3,5]
4. '*'优先级高于'+',直接入栈 → op:[+, *]
5. '2'压入num → num:[3,5,2]
6. 表达式结束,处理剩余运算符:- 先处理 '*' → 5 * 2=10 → num:[3,10]- 处理 '+' → 3+10=13 → 输出13示例表达式处理模拟2:7 - (3+2 * 5)
1. '7'压入 → num:[7]
2. '-' 入栈 → op:[-]
3. '(' 入栈 → op:[-, (]
4. '3'入栈 → num:[7,3]
5. '+' 入栈(栈顶是'(',优先不计算) → op:[-, (, +]
6. '2'入栈 → num:[7,3,2]
7. '*'优先级高于'+',入栈 → op:[-, (, +, *]
8. '5'入栈 → num:[7,3,2,5]
9. 遇到')':循环处理运算符到'('- 处理 '*' → 2 * 5=10 → num:[7,3,10]- 处理 '+' → 3+10=13 → num:[7,13]- 弹出 '(' → op:[-]
10.处理剩余运算符 '-' → 7-13= -6 → 输出-6
*/
此篇参考了acwing算法基础课。