栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

使用栈完成逆波兰计算器

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用栈完成逆波兰计算器

要求:

1.输入一个逆波兰表达式【后缀表达式】,使用栈(stack)完成计算其结果。

2.支持小括号和多位数。

代码实现
 public static void main(String[] args) {
        //先定义一个逆波兰表达式
        //3 4 + 5 * 6 -
        //为了方便,逆波兰表达式的数字和符号用空格隔开
        String suffixexpression = "3 4 + 5 * 6 - ";
        //思路
        //1.先将"3 4 + 5 * 6 - " =》 放到ArrayList中
        //2.将ArrayList 传递给一个方法,遍历ArrayList 配合栈完成计算
        List rpnList = getListString(suffixexpression);
        System.out.println(rpnList);
        int res = calculate(rpnList);
        System.out.println("计算的结果为:"+res);
    }

    
    public static List getListString(String suffixexpression) {
        //将suffixexpression进行分割
        String[] split = suffixexpression.split(" ");
        List list = new ArrayList();
        for (String a : split) {
            list.add(a);
        }
        return list;
    }

    
    public static int calculate(List ls) {
        //创建一个栈
        Stack stack = new Stack<>();
        //遍历 ls
        for (String item : ls) {
            //使用正则表达式来取出数
            if (item.matches("\d+")) {//匹配多位数
                //入栈
                stack.push(item);
            } else {
                //pop出两个数,并进行计算,再入栈
                int num2 = Integer.parseInt(stack.pop());
                int num1 = Integer.parseInt(stack.pop());
                int res = 0;
                if (item.equals("+")) {
                    res = num1 + num2;
                } else if (item.equals("-")) {
                    res = num1 - num2;
                } else if (item.equals("*")) {
                    res = num1 * num2;
                } else if (item.equals("/")) {
                    res = num1 / num2;
                } else {
                    throw new RuntimeException("运算符错误");
                }
                //把res入栈
                stack.push(res+"");
            }
        }
        //将最后的结果返回
        return Integer.parseInt(stack.pop());
    }
效果展示:
[3, 4, +, 5, *, 6, -]
计算的结果为:29

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/695286.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号