逆波兰计算器(上))
栈——通过逆波兰计算式构建计算器
思路分析
已知后缀进行计算
(3+4)×5-6 =>3 4 + 5 × 6 -
- 从左至右扫描,将3和4压入堆栈;
- 遇到+运算符,因此弹出4和3(4为栈顶元素,3为次顶元素),计算出3+4的值,得7,再将7入栈;
- 将5入栈;
- 接下来是×运算符,因此弹出5和7,计算出7×5=35,将35入栈;
- 将6入栈;
- 最后是-运算符,计算出35-6的值,即29,由此得出最终结果(下一个-顶部)
代码详解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| public class PolandNotation { public static void main ( String[] args ) { String suffixExpression = "4 5 * 8 - 60 + 8 2 / +";
List<String> reList = getListStrings ( suffixExpression ); System.out.println ("reList="+reList ); int res=calculate ( reList ); System.out.println ("运算结果为: "+res ); }
public static List<String> getListStrings ( String suffixEpression ) { String[] spilt=suffixEpression.split ( " " ); List<String> list = new ArrayList<String> ( ); for ( String element : spilt ) { list.add( element );
} return list; }
public static int calculate ( List<String> ls) { Stack<String> stack = new Stack<> ( ); for ( String s : ls ) { if ( s.matches ("\\d+" ) ){ stack.push ( s ); }else { int num2 = Integer.parseInt (stack.pop ( )); int num1 = Integer.parseInt (stack.pop ( )); int res=0; if ( s.equals ( "+" ) ) { res = num1 + num2; } else if ( s.equals ( "-" ) ) { res = num1 - num2; } else if ( s.equals ( "*" ) ) { res = num1 * num2; } else if ( s.equals ( "/" ) ) { res = num1 / num2; }else { throw new RuntimeException ( "运算符完毕" ); } stack.push ( ""+res ); } } return Integer.parseInt (stack.pop ( )); } }
|
结果:
这里有张图片: