侧边栏壁纸
博主头像
小顺

一帆风顺 ⛵️⛵️⛵️

  • 累计撰写 64 篇文章
  • 累计创建 0 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

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

小顺
2021-07-22 / 0 评论 / 0 点赞 / 107 阅读 / 203 字

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

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();
    }

}
0

评论区