用堆栈实现后缀表达式的计算

proheart
public class PolandExpressionDemo {
    /* 计算逆波兰表达式(后缀表达式)结果
       假设每个数字或者字符之间用空格隔开
       4 * 5 - 8 + 60 + 8 / 2 = 4 5 * 8 - 60 + 8 2 / +
     */
    public double calculatePoland(String exp) {
        String[] strings = exp.split(" ");
        Stack<Double> stack = new Stack<>();
        for (String s: strings) {
            double n1, n2;
            switch (s) {
                case "*":
                    n1 = stack.pop();
                    n2 = stack.pop();
                    stack.push(n1 * n2);
                    break;
                case "/":
                    n1 = stack.pop();
                    n2 = stack.pop();
                    stack.push(n2 / n1);
                    break;
                case "+":
                    n1 = stack.pop();
                    n2 = stack.pop();
                    stack.push(n1 + n2);
                    break;
                case "-":
                    n1 = stack.pop();
                    n2 = stack.pop();
                    stack.push(n2 - n1);
                    break;
                default:
                    stack.push(Double.parseDouble(s));
                    break;
            }
        }
        return stack.pop();
    }

    public static void main(String[] args) {
        PolandExpressionDemo app = new PolandExpressionDemo();
        System.out.println(app.calculatePoland("4 5 * 8 - 60 + 8 2 / +"));
    }
}
阅读 972

来刷算法
Learn data structure and algorithm using java.

Developer, Java & Android

38 声望
20 粉丝
0 条评论

Developer, Java & Android

38 声望
20 粉丝
文章目录
宣传栏