Java用栈实现逆波兰表达式数组的计算

发布于 2021-07-22  44 次阅读


妙了,上学时没好好学习,冲冲冲!

Start类代码没变,和上一篇一样。

main方法代码如下:

package com.apesblog.Stack;

public class ReversePolishNotation {
    public static void main(String[] args) {
        // 中缀表达式3*(17-15)+18/6的逆波兰表达式如下
        String[] notation = { "3", "17", "15", "-", "*", "18", "6", "/", "+" };
        System.out.print("逆波兰运算结果为:" + calculate(notation));
    }

    private static int calculate(String[] notation) {
        Stack<Integer> stack = new Stack<Integer>();
        for (int i = 0; i < notation.length; i++) {
            Integer x;
            Integer y;
            switch (notation[i]) {
            case "+":
                y = stack.pop();
                x = stack.pop();
                stack.push(x + y);
                break;
            case "-":
                y = stack.pop();
                x = stack.pop();
                stack.push(x - y);
                break;
            case "*":
                y = stack.pop();
                x = stack.pop();
                stack.push(x * y);
                break;
            case "/":
                y = stack.pop();
                x = stack.pop();
                stack.push(x / y);
                break;

            default:
                stack.push(Integer.parseInt(notation[i]));
                break;
            }
        }
        return stack.pop();
    }

}

运行结果如下: