妙了,上学时没好好学习,冲冲冲!
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();
    }
}
                
        
      
        
      
评论区