中后缀转换
后缀表达式又称之为逆波兰表示法;
中缀表达式a + b*c + (d * e + f) * g,其转换成后缀表达式则为a b c * + d e * f + g * +;0
转换过程需要用到栈,具体过程如下:
1)如果遇到操作数,我们就直接将其输出;
2)如果遇到操作符,则我们将其放入到栈中,遇到左括号时我们也将其放入栈中;
3)如果遇到一个右括号,则将栈元素弹出,将弹出的操作符输出直到遇到左括号为止;注意,左括号只弹出并不输出;
4)如果遇到任何其他的操作符,如(“+”, “*”,“(”)等,从栈中弹出元素直到遇到发现更低优先级的元素(或者栈为空)为止。弹出完这些元素后,才将遇到的操作符压入到栈中。有一点需要
注意,只有在遇到" ) "的情况下我们才弹出" ( ",其他情况我们都不会弹出" ( ";
5)如果我们读到了输入的末尾,则将栈中所有元素依次弹出;
快速计算:
1)先按照运算符的优先级对中缀表达式加括号,变成( ( a+(b*c) ) + ( ((d*e)+f) *g ) );
2)将运算符移到括号的后面,变成((a(bc)*)+(((de)*f)+g)*)+;
3)去掉括号,得到abc*+de*f+g*+;
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <iostream> 4 #include <string.h> 5 #include<vector> 6 #include <stack> 7 using namespace std; 8 int Priority(char a,char b) 9 { 10 if((a == '*' || a == '/') ) 11 return 1; 12 else return 0; 13 } 14 int main() 15 { 16 stack<char> sta; 17 char s[50]; 18 char ans[50];//装结果的数组 19 20 while(scanf("%s",s) != EOF) 21 { 22 int i = 0; 23 int j = 0;//控制答案数组的 24 int k = 0;//是否输出空格 25 for(i;s[i];i++) 26 { 27 if(s[i] == '(')//左括号直接压入 28 sta.push(s[i]); 29 else if(s[i] == ')')//右括号 30 { 31 if(k == 1) 32 { 33 ans[j++] = ' '; 34 k = 0; 35 } 36 while(sta.top() != '(')//弹出栈中左括号之前的符号 37 { 38 ans[j++] = sta.top(); 39 ans[j++] = ' '; 40 sta.pop(); 41 } 42 sta.pop();//弹出左括号 43 } 44 else if((s[i] >= '1' && s[i] <= '9') || s[i] == '.') 45 { 46 ans[j++] = s[i]; 47 k = 1; 48 } 49 else//符号位+-*/ 50 { 51 if(k == 1) 52 { 53 ans[j++] = ' '; 54 k = 0; 55 } 56 if((s[i] == '-' || s[i] == '+') && i == 0)//第一个是正负号 57 { 58 if(s[i] == '-') 59 ans[j++] = '-'; 60 } 61 else if((s[i] == '-' || s[i] == '+') && i != 0 && s[i-1] == '(' )//有负数情况 62 { 63 if(s[i] == '-') 64 ans[j++] = s[i] ; 65 sta.pop();//删除左括号 66 while(s[++i] != ')') 67 { 68 ans[j++] = s[i]; 69 } 70 ans[j++] = ' '; 71 } 72 else 73 { 74 //弹出所有优先级大于该运算符的栈顶元素,然后将该运算符入栈 75 while(!sta.empty() && Priority(sta.top(),s[i]) ) 76 { 77 ans[j++] = sta.top(); 78 ans[j++] = ' '; 79 sta.pop(); 80 } 81 sta.push(s[i]);//优先级低,直接放入 82 } 83 } 84 } 85 if(k == 1) 86 { 87 ans[j++] = ' '; 88 k = 0; 89 } 90 while(!sta.empty())//弹出栈中剩余元素 91 { 92 ans[j++] = sta.top(); 93 ans[j++] = ' '; 94 sta.pop(); 95 } 96 ans[j-1]=0; 97 puts(ans); 98 } 99 }