穿越隧道
递归地进行中序遍历**,中序遍历需要比较运算符之间的优先级,此处用括号体现相同运算符的优先级关系。
缺点:(耗时,对我而言还没掌握。。)
栈模拟,定义运算符的优先级,每当有一个新的运算符进入符号栈时,来与符号栈顶的符号优先级进行比较。
#includeusing namespace std; const int N = 1e4 + 10; string s; stack num;//操作数 stack op;//运算符 unordered_map 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 if(c == '/') x = a / b; num.push(x); } int main(){ cin >> s; int len = s.size(); for(int i = 0; i < len; i++){ if(isdigit(s[i])){//因操作数可能一位,也可能为十位,百位 int x = 0;//计算操作数。 int j = i;//操作数长度的初始位置。 while(j < len && isdigit(s[j])){ x = x * 10 + (s[j] - '0'); j++; } num.push(x);//将该数字存入栈中 i = j - 1;//i移到操作数的尾部 } else if(s[i] == '(') op.push(s[i]); else if(s[i] == ')'){//意味着要算一个括号中的所有式子。 while(op.top() != '('){//在运算符栈中进行运算符的使用,直到碰见左括号 eval();//进行运算操作。 } op.pop();//意味着要将左括号出栈。 } else{//说明s[i]为操作符:+,-,*,/,此时要比较运算符的优先级 while(op.size() && pr[op.top()] >= pr[s[i]]){//运算符优先级相等,从左往右计算。所以,此处只为大于等于 eval();//先计算运算符高的。 } //计算完运算符优先级高的后,已经出栈了。此时将优先级低的运算符进栈 op.push(s[i]); } } while(op.size()) eval();//可能符号栈中还存在一些运算符 cout << num.top() << endl; return 0; }



