07 逆波兰计算器(后缀表达式求值)

逆波兰计算器

1. 思路分析:

(3+4)×5-6 对应的后缀表达式就是 3 4 + 5 × 6 - , 针对后缀表达式求值步骤如下:

  1. 从左至右扫描,将 3 和 4 压入堆栈;
  2. 遇到+运算符,因此弹出 4 和 3(4 为栈顶元素,3 为次顶元素),计算出 3+4 的值,得 7,再将 7 入栈;
  3. 将 5 入栈;
  4. 接下来是×运算符,因此弹出 5 和 7,计算出 7×5=35,将 35 入栈;
  5. 将 6 入栈;
  6. 最后是-运算符,计算出 35-6 的值,即 29,由此得出最终结果。

2. 代码实现:

/**
 * 逆波兰表达式(后缀表达式)求值
 */
public class PolandNotation {
    /**
     * 测试
     * @param args
     */
    public static void main(String[] args) {
        String expression = "3 4 + 5 * 6 -";
        List<String> list = stringToList(expression);
        int result = calculate(list);
        System.out.println("计算结果为:" + result);
    }

    /**
     * 具体计算后缀表达式
     * @param list 表示后缀表达式的ArrayList
     * @return 返回计算结果
     */
    public static int calculate(List<String> list) {
        int result = 0;
        Stack<String> stack = new Stack<>();
        for (String element : list) {
            if (element.matches("\\d+")) {
                stack.push(element);
            } else if ("+".equals(element)) {
                int num1 = Integer.parseInt(stack.pop());
                int num2 = Integer.parseInt(stack.pop());
                result = num2 + num1;
                stack.push("" + result);
            } else if ("-".equals(element)) {
                int num1 = Integer.parseInt(stack.pop());
                int num2 = Integer.parseInt(stack.pop());
                result = num2 - num1;
                stack.push("" + result);
            } else if ("*".equals(element)) {
                int num1 = Integer.parseInt(stack.pop());
                int num2 = Integer.parseInt(stack.pop());
                result = num2 * num1;
                stack.push("" + result);
            } else if ("/".equals(element)) {
                int num1 = Integer.parseInt(stack.pop());
                int num2 = Integer.parseInt(stack.pop());
                result = num2 / num1;
                stack.push("" + result);
            } else {
                throw new RuntimeException("表达式有误!");
            }
        }
        return Integer.parseInt(stack.pop());
    }

    /**
     * 将字符串类型的表达式转换为ArrayList
     * @param expression 后缀表达式
     * @return 返回表示后缀表达式的ArrayList
     */
    public static List<String> stringToList(String expression) {
        List<String> list = new ArrayList<>();
        String[] split = expression.split(" ");
        for (String s : split) {
            list.add(s);
        }
        return list;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值