采用栈实现逆波兰表达式

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

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

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

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

    /**
   * 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,由此得出最终结果
   */
    public static Integer excute(ArrayList<String> anitPoland) {
        Stack<Integer> 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;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值