送外卖小公司OA

2018-10-24  本文已影响0人  manayuan

中缀表达式转后缀表达式的方法:

输入是用space分割的expression,数字可以是negative number,不用处理括号

public class EvalExpression {
    public static void main(String[] args) {
        String exp = "6 / 3 / 2";
        int res = eval(exp);
        System.out.println(res);
    }
    static int eval(String exp) {
        String[] tokens = exp.split(" ");
        Stack<Integer> nums = new Stack<Integer>();
        Stack<String> operators = new Stack<String>();
        
        Set<String> operand = new HashSet<String>();
        operand.add("+");
        operand.add("-");
        operand.add("*");
        operand.add("/");
        
        for (String token : tokens) {
            if (operand.contains(token)) {
                if (operators.isEmpty()) {
                    operators.push(token);
                }
                else {
                    if (token.equals("+") || token.equals("-")) {
                        while (! operators.isEmpty()) {
                            String tmp = operators.pop();
                            int num2 = nums.pop(), num1 = nums.pop();
                            nums.push(operate(num1, num2, tmp));
                        }                        
                    }
                    if (token.equals("*") || token.equals("/")) {
                        while (! operators.isEmpty() && (operators.peek().equals("*") || operators.peek().equals("/"))) {
                            String tmp = operators.pop();
                            int num2 = nums.pop(), num1 = nums.pop();
                            nums.push(operate(num1, num2, tmp));
                        } 
                    }
                    operators.push(token);
                }
            }
            else {
                nums.push(Integer.parseInt(token));
            }
        }
        while (! operators.isEmpty()) {
            String tmp = operators.pop();            
            int num2 = nums.pop(), num1 = nums.pop();
            nums.push(operate(num1, num2, tmp));
        }
        return nums.pop();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读