求后缀表达式转中缀表达式的代码,请各位大神用栈来解,其他的如树等太过高深,蒟蒻一只不会用。拜托拜托!感激不尽!
2条回答 默认 最新
- Al_assad 2017-02-08 05:08关注
从左至右扫描表达式,遇到数字时,将数字压入堆栈,遇到运算符时,弹出栈顶的两个数,用运算符对它们做相应的计算(次顶元素 op 栈顶元素),并将结果入栈;重复上述过程直到表达式最右端,最后运算得出的值即为表达式的结果。
例如后缀表达式 “3 4 + 5 × 6 -”:
(1) 从左至右扫描,将 3和4 压入堆栈;
(2) 遇到 +运算符,因此弹出4和 3(4 为栈顶元素, 3为次顶元素,注意与前缀表达式做比较),计算出 3+4的值,得7 ,再将7入栈;
(3) 将5入栈;
(4) 接下来是 ×运算符,因此弹出5和 7,计算出7×5=35 ,将35入栈;
(5) 将6入栈;
(6) 最后是 -运算符,计算出35-6的值,即 29,由此得出最终结果。// 计算后缀表达式的结果 public static int toValue(StringBuffer postfix){ Stack<Integer> stack = new Stack<Integer>(); for(int i=0;i<postfix.length();i++){ char ch = postfix.charAt(i); if(ch>='0' && ch<='9'){ String value =""; while(ch!= ' '){ value += ch; ch = postfix.charAt(++i); } stack.push(Integer.parseInt(value)); } else{ if(ch!= ' '){ int y = stack.pop(); int x = stack.pop(); switch(ch){ case '+':stack.push(x+y); break; case '-': stack.push(x-y) ; break; case '*': stack.push(x*y); break; case '/' : stack.push(x/y);break; } } } } return stack.pop(); }
如果只是为了将后缀表达式转为中缀表达式,在以上流程中将出栈的数值和符号按照中缀表达式的格式打印出来(或储存为字符串就可以了);
//后缀表达式转化为中缀表达式 public static String postfixToInfix(StringBuilder postfix){ Stack<String> stack = new Stack<String>(); //记录操作数 char sign; //记录前一个操作码 for(int i=0;i<postfix.length();i++){ char ch = postfix.charAt(i); if(ch>='0' && ch<='9'){ String value =""; while(ch!= ' '){ value += ch; ch = postfix.charAt(++i); } stack.push(value); } else{ if(ch!= ' '){ String y = stack.pop(); //两个操作数出栈 String x = stack.pop(); if((ch == '*' || ch == '/') && (sign == '+' || sign == '-')){ stack.push("("+x+")"+ch+y); }else{ stack.push(x+ch+y) } sign = ch; } } } } return stack.pop(); }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 2无用