栈练习--Dijkstra的双栈算术表达式求值算法
此法还有待完善,比如在做除法运算时未判断除数是否为0,而且也可以加以扩展,比如log、sin、操作符优先级。。
1 public class Evaluate { 2 3 public static void main(String[] args) { 4 String steam = "( 1 + ( 2 + 3 ) * ( 4 * 5 ) ) )"; 5 // String steam = "( ( 1 + sqrt ( 5.0 ) ) / 2.0 )"; 6 Stack<String> ops = new Stack<String>(); 7 Stack<Double> vals = new Stack<Double>(); 8 9 String[] steams = steam.split(" "); 10 11 for(int i=0; i<steams.length; i++) { 12 //读取字符,如果是运算符就压入栈 13 String s = steams[i]; 14 /*char item = steam.charAt(i); 15 String s = String.valueOf(item);*/ 16 17 18 if(s.equals("(")) { 19 ; 20 }else if(s.equals("+")) { 21 ops.push(s); 22 }else if(s.equals("-")) { 23 ops.push(s); 24 }else if(s.equals("*")) { 25 ops.push(s); 26 }else if(s.equals("/")) { 27 ops.push(s); 28 }else if(s.equals("sqrt")) { 29 ops.push(s); 30 }else if(s.equals(")")) { 31 //如果字符为“)”则弹出运算符和操作数,计算结果并压入栈 32 String op = ops.pop(); 33 double v = vals.pop(); 34 if(op.equals("+")) { 35 v = vals.pop() + v; 36 }else if(op.equals("-")) { 37 v = vals.pop() - v; 38 }else if(op.equals("*")) { 39 v = vals.pop() * v; 40 }else if(op.equals("/")) { 41 v = vals.pop() / v; 42 }else if(op.equals("sqrt")) { 43 v = Math.sqrt(v); 44 } 45 vals.push(v); 46 }else { 47 //如果字符既非运算符也不是括号,将它作为double值压入栈 48 vals.push(Double.parseDouble(s)); 49 } 50 } 51 System.out.println(vals.pop()); 52 } 53 }