代码利用栈来实现算术表达式的求值功能,仅用于举例说明栈的用例,没有考虑运算符的优先级,并且要求表达式的各个部分必须用空格分隔:
package com.mycode.algorithms.stack; import java.util.HashMap; import java.util.Map; import java.util.Stack; public class Evaluate { static Stack<String> ops = new Stack<String>(); static Stack<Double> params = new Stack<Double>(); static Map<String,String> VALIDATE_OPS = new HashMap<String,String>(); static { VALIDATE_OPS.put("+", "+"); VALIDATE_OPS.put("-", "-"); VALIDATE_OPS.put("*", "*"); VALIDATE_OPS.put("/", "/"); } public static void main(String[] args) { System.out.println(calcute("( 5 + ( 3 * ( 4 + 5 ) ) + 100 )")); } public static void clear(){ ops.clear(); params.clear(); } public static boolean isOps(String symbol){ return VALIDATE_OPS.get(symbol)!=null; } public static Double calcuteValue(String symbol,Double v1,Double v2){ String op = VALIDATE_OPS.get(symbol); if(op.equals("+")){ return v1 + v2; }else if(op.equals("-")){ return v1 -v2; }else if(op.equals("*")){ return v1 * v2; }else if(op.equals("/")){ return v1 / v2; } throw new RuntimeException("not supported operation:"+op); } public static Double calcute(String expression){ clear(); for(String symbol : expression.split(" ")){ if(symbol.trim().equals("") || symbol.equals("(")) continue; if(isOps(symbol)){ ops.add(symbol); }else if(symbol.equals(")")){ params.add(calcuteValue(ops.pop(), params.pop(), params.pop())); }else{ params.add(Double.valueOf(symbol)); } System.out.println(params); System.out.println(ops); System.out.println("===================="); } if(!ops.isEmpty()){ params.add(calcuteValue(ops.pop(), params.pop(), params.pop())); } return params.pop(); } }
[5.0] [] ==================== [5.0] [+] ==================== [5.0, 3.0] [+] ==================== [5.0, 3.0] [+, *] ==================== [5.0, 3.0, 4.0] [+, *] ==================== [5.0, 3.0, 4.0] [+, *, +] ==================== [5.0, 3.0, 4.0, 5.0] [+, *, +] ==================== [5.0, 3.0, 9.0] [+, *] ==================== [5.0, 27.0] [+] ==================== [5.0, 27.0] [+, +] ==================== [5.0, 27.0, 100.0] [+, +] ==================== [5.0, 127.0] [+] ==================== 132.0