只涉及+ - * / ()
中缀表达式直接求值(使用两个栈:数字栈、符号栈)
- 如果为左括号,直接入符号栈。
- 如果为数字,直接入数字栈。
- 如果当前指向运算符优先级<=符号栈栈顶优先级:从数字栈中弹出两个数字,符号栈中弹出一个数字,进行运算,运算结果压入数字栈。
- 如果当前指向运算符优先级>符号栈栈顶优先级:直接入符号栈。
- 如果为右括号,不断出栈运算,直到遇到左括号停止运算,左括号也要出栈。
得到两个栈后
- 如果符号栈为空,则直接返回数字栈中栈顶结果(只有一个元素)。
- 否则,还要运算直到符号栈为空。
#include <iostream>
#include <cstdio>
#include <map>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <cstring>
#include <cmath>
#include <stack>
using namespace std;
stack<int> s_num;
stack<int> s_symbol;
int priority(char sym) {
int val = 0;
switch(sym) {
case '*':
case '/':
val = 1;
break;
case '+':
case '-':
val = 0;
break;
case '(':
case ')':
val = -1;
break;
}
return val;
}
int compute(int n1, int n2, char ch) {
switch(ch) {
case '*':
return n1*n2;
case '/':
return n2/n1;
case '+':
return n1+n2;
case '-':
return n2-n1;
}
return -1;
}
bool is_digital(char ch) {
return ch>='0' && ch<='9';
}
void operate() {
int n1 = s_num.top();
s_num.pop();
int n2 = s_num.top();
s_num.pop();
char ch = s_symbol.top();
s_symbol.pop();
int res = compute(n1, n2, ch);
s_num.push(res);
}
int main() {
freopen("i.txt", "r", stdin);
string str;
cin >> str;
for(int i = 0; i < (int)str.size(); i++) {
if(str[i] == '(') {
s_symbol.push('(');
continue;
}
else if(str[i] == ')') {
while(true) {
char ch = s_symbol.top();
if(ch == '(') {
s_symbol.pop();
break;
}
else {
operate();
}
}
continue;
}
if(is_digital(str[i])) {
int i2 = i;
while(is_digital(str[i2]) && i2<=(int)str.size()) {
i2++;
}
string t = str.substr(i, i2-i);
stringstream sstr(t);
int num;
sstr >> num;
s_num.push(num);
i = i2-1;
}
else {
if(s_symbol.empty())
s_symbol.push(str[i]);
else {
char t = s_symbol.top();
if(priority(str[i]) <= priority(t)) {
operate();
}
s_symbol.push(str[i]);
}
}
}
if(!s_symbol.empty()) {
while(!s_symbol.empty()) {
operate();
}
}
cout << s_num.top() << endl;
return 0;
}