• 9、栈-逆波兰计算器(输入为逆波兰表达式)


    来源:https://www.bilibili.com/video/BV1B4411H76f?p=36

    一、前缀表达式、中缀表达式、后缀表达式(逆波兰表达式)

    前缀表达式:又叫波兰式,它的运算符位于数据前面,例如:− × + 3 4 5 6。计算机对其进行运算时从右到左扫描入栈,遇到运算符时弹出数据,利用运算符进行计算,得到的数据再次入栈,如此循环。

    中缀表达式:就是我们常见的表达式,上面的前缀表达式对应的中缀表达式为:(3+4)× 5 − 6,这对计算机的运算来说不太好操作。

    后缀表达式:又叫逆波兰表达式,运算符位于数据后面,上面的式子对应的后缀表达式为:3 4 + 5 × 6 -

     

    这里我们先实现一个简单的,输入为现成的后缀表达式,得到输出结果。即按照从左到右的顺序进行:【遇到数据入栈,遇到符号计算,得到结果继续入栈的循环操作】

    二、实现

     1     public static void main(String[] args) {
     2         String suffixException = "30 4 + 5 * 6 -";
     3 
     4         List<String> array = getArray(suffixException);
     5         System.out.println(array);
     6 
     7         int res = calculate(array);
     8         System.out.println(res);
     9     }
    10 
    11     //将字符串转为数组的形式
    12     public static List<String> getArray(String suffixException){
    13         String[] split = suffixException.split(" ");
    14 
    15         List<String> list = new ArrayList<>();
    16 
    17         for (String s : split) {
    18             list.add(s);
    19         }
    20         return list;
    21     }
    22 
    23     //计算逆波兰表达式
    24     public static int calculate(List<String> ls){
    25         Stack<String> stack = new Stack<>();
    26         for (String item : ls) {
    27             //用matches方法判断取出来的内容是否匹配对应的正则表达式(\d+),即匹配的是一个多位数
    28             if(item.matches("\d+")){
    29                 stack.push(item);//是数字就入栈
    30             }else {
    31                 int num1 = Integer.parseInt(stack.pop());
    32                 int num2 = Integer.parseInt(stack.pop());
    33                 int res = 0;
    34                 if(item.equals("+")){
    35                     res = num2 + num1;
    36                 }else if(item.equals("-")){
    37                     res = num2 - num1;
    38                 }else if(item.equals("*")){
    39                     res = num2 * num1;
    40                 }else if(item.equals("/")){
    41                     res = num2 / num1;
    42                 }else {
    43                     throw new RuntimeException("运算符错误:"+item);
    44                 }
    45                 stack.push(""+res);//计算完成,转为字符串,入栈
    46             }
    47         }
    48         return Integer.parseInt(stack.pop());//最后留在栈中的就是结果
    49     }

    结果

    [30, 4, +, 5, *, 6, -]
    164

    这里我们手动输入了逆波兰表达式,正确的姿势应该是将中缀表达式转换成逆波兰表达式,之后进行计算。

  • 相关阅读:
    html_Dom
    html_javascript
    html_之css
    协程
    进程和线程的总结
    html_基础标签
    html_头部<meta>设置
    Python_queue单项队列
    Python_paramiko模块
    Python_多进程multiprocessing
  • 原文地址:https://www.cnblogs.com/zhao-xin/p/13154249.html
Copyright © 2020-2023  润新知