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

采用栈实现逆波兰表达式

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

采用栈实现逆波兰表达式

从左至右扫描表达式,遇到数字时,将数字压入堆栈,遇到运算符时,弹出栈顶的两个数,用运算符对它们做相应的计算(次顶元素 和 栈顶元素),并将结果入栈;重复上述过程直到表达式最右端,最后运算得出的值即为表达式的结果

我们完成一个逆波兰计算器,要求完成如下任务:

    输入一个逆波兰表达式(后缀表达式),使用栈(Stack), 计算其结果支持小括号和多位数整数,因为这里我们主要讲的是数据结构,因此计算器进行简化,只支持对整数的计算。思路分析代码完成
public class LastCalculator {
    public static void main(String[] args) {
        String antiPoland = "3 4 + 5 * 6 -";
        ArrayList anitPoland = spitAnitPoland(antiPoland);
        System.out.println(anitPoland);
        Integer excute = excute(anitPoland);
        System.out.println(excute);
    }

    // 将得到的逆波兰字符串转换成数组存储
    public static ArrayList spitAnitPoland(String antiPoland){
        ArrayList list = new ArrayList<>();
        String[] s = antiPoland.split(" ");
        for (String s1 : s) {
            list.add(s1);
        }
        return list;
    }

    
    public static Integer excute(ArrayList anitPoland) {
        Stack numStack = new Stack<>();
        for (String item : anitPoland) {
            // 1. 从左至右扫描,将3和4压入堆栈;
            if (item.matches("\d+")) {
                numStack.push(Integer.parseInt(item));
            }else {
                Integer num2 = numStack.pop();
                Integer num1 = numStack.pop();
                Integer calc = calc(num1, num2, item);
                numStack.push(calc);
            }
        }
        return numStack.pop();
    }

    // 计算方法
    public static Integer calc(Integer num1,Integer num2,String oper) {
        int res;
        if (oper.equals("+")) {
            res = num1 + num2;
        } else if (oper.equals("-")) {
            res = num1 - num2;
        } else if (oper.equals("*")) {
            res = num1 * num2;
        } else if (oper.equals("/")) {
            res = num1 / num2;
        } else {
            throw new RuntimeException("运算符有误");
        }
        return res;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/704042.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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