前缀表达式:ios
不含括号的算术表达式,并且是将运算符写在前面,操做数写在后面的表达式。git
求法:测试
首先从右往左扫描表达式,从右边第一个字符判断,若是当前字符是数字,则一直到字符串的末尾再记录下来;若是是运算符,则将右边最近的两个数字串作相应的运算,以此做为一个新串并记录下来。一直扫描到最左端中止。spa
例子:(a + b)* (c + d) : *+ab+cd。理解:根据优先级,把数字位置不一样,有那两个能够作运算,将运算符写在对应的数字前面,作完数字以后还有的元素,放在最前面。3d
中缀表达式:code
是一个通用的算术或逻辑公式表达方法,操做符是以中缀形式处于操做数中间,即咱们经常使用的算术表达方式。对象
注意:中缀记法中括号是必须的。计算过程当中用括号将相应的操做数和运算符括起来,用于指示运算的次序。blog
后缀表达式:ci
不包含括号,运算符放在两个运算对象的后面,全部的计算按运算符出现的顺序,严格从左向右进行(再也不考虑运算符的优先规则)。
字符串
例子:(2 + 3)* 4 : 23+4*。理解:和前缀区别不大,是从左往右,保证数字字符的顺序位置不变便可。
分析过程:
参考代码:
#include<iostream> #include<stack> #include<string.h> #include<ctype.h>//用于类型判断 using namespace std; stack<char> op; // 操做符栈 char ans[1000]; int priority(char ch){ switch(ch){ case '(' : return -1; case '+': case '-': return 1; case '/': case '*': return 2; } } bool isOperator(char ch){ if(ch == '+' || ch == '-' || ch == '/' || ch == '*'){ return true; } return false; } bool isCharacter(char ch){ if(ch >= '0' && ch <= '9' || ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z'){ return true; } return false; } int main(){ string str; while(cin >> str){ int k = 0; int len = str.length(); str[len] = '#'; for(int i = 0; i <= len; i ++){// isdigit(str[i]) || isalpha(str[i]) if(isCharacter(str[i])){ ans[k ++] = str[i]; } else if(isOperator(str[i])){ // ans[k ++] = '#'; if(op.empty()){ op.push(str[i]); } else{ while(!op.empty() && priority(op.top()) >= priority(str[i])){ ans[k ++] = op.top(); op.pop(); } op.push(str[i]); } } else if(str[i] == '('){ op.push(str[i]); } else if(str[i] == ')'){ while(op.top() != '('){ ans[k ++] = op.top(); op.pop(); } op.pop(); } else if(str[i] == '#'){ while(!op.empty()){ ans[k ++] = op.top(); op.pop(); } } } cout << ans << endl; } return 0; }测试截图:
以上就是这篇的内容,欢迎指出错误和不足之处,谢谢!