逆波兰计算器的完整代码

前置知识:

 

 

将中缀表达式转为List方法:

 //将一个中缀表达式转成中缀表达式的List
    //即:(30+42)*5-6 ==》[(, 30, +, 42, ), *, 5, -, 6]
    public static List<String> toIndixExpressionList(String s) {
        //定义一个List,存放中缀表达式对应的内容
        List<String> ls = new ArrayList<String>();
        int i = 0; //这是一个指针,用于遍历 中缀表达式字符串
        String str = ""; //对多位数的拼接
        char c; //每遍历到一个字符,我需要加入到ls
        do {
            //如果是一个字符,直接添加到list
            if ((c = s.charAt(i)) < '0' || (c = s.charAt(i)) > '9') {
                ls.add("" + c);
                i++; //指针后移
            } else { //如果是一个数,需要考虑多位数
                str = ""; //将字符串置空
                while ((i < s.length()) && (c = s.charAt(i)) >= '0' && (c = s.charAt(i)) <= '9') {
                    str += c;
                    i++;
                }
                ls.add(str);
            }
        } while (i < s.length());
        return ls;
    }

将中缀表达式转化为后缀表达式(删除小括号):
 

 //将得到的中缀表达式对应的 List => 后缀表达式对应的 List
    // [(, 30, +, 42, ), *, 5, -, 6] ==》 30,42,+,5,*,6,-
    public static List<String> parseSuffixExpressionList(List<String> ls){
        //定义两个栈
        Stack<String> operStack = new Stack<String>();   //符号栈
        //因为 resStack ,这个栈整个转换过程中,没有pop操作,而且后面我们还需要逆序输出
        //因此我们这里使用 List<String> resList作为结果的存储
        List<String> resList = new ArrayList<String>();

        //遍历ls
        for (String item :ls) {
            //如果是一个数就直接加入到resList
            if(item.matches("\\d+")){
                resList.add(item);
            }else if (item.equals("(")){
                 operStack.push(item);
            }else if(item.equals(")")){
                //如果是右括号,则依次弹出 operStack 栈顶的运算符,并压入s2,
                // 直到遇到左括号为止,此时将这一对括号丢弃
                while (!operStack.peek().equals("(")) {
                    String temp = operStack.pop();
                    resList.add(temp);
                }
                    operStack.pop(); //将 ( 弹出符号栈,消除小括号
            }else {
                //当item的优先级 <= operStack 栈顶运算符,
                // 将 operStack 栈顶的运算符弹出并加入到 resList中
                // 再次与新 operStack 中新的栈运算符相比较
                while (operStack.size() != 0 && Operation.getValue(operStack.peek()) >= Operation.getValue(item)){
                    resList.add(operStack.pop());
                }
                //还需要将item压入栈中
                operStack.push(item);
            }
        }
        //将operStack中剩余的运算符依次弹出并加入到resList中
        while (operStack.size()!=0){
            resList.add(operStack.pop());
        }
        return resList; //注意因为是存放到List,因此按顺序输出就是对应的后缀表达式
    }

运算符的优先级:

//编写一个类 Operation 可以返回一个运算符 ,对应的优先级
class Operation{
    private static int ADD = 1;
    private static int SUB = 1;
    private static int MUL = 2;
    private static int DIV = 2;

    //写一个方法,返回对应的优先级数字
    public static int getValue(String operation){
        int result = 0;
        switch (operation){
            case "+":
                result = ADD;
                break;
            case "-":
                result = SUB;
            break;
            case "*":
                result = MUL;
            break;
            case "/":
                result = DIV;
            break;
            default:
                System.out.println("不存在该运算符~");
                break;
        }
        return result;
    }
}

 运算方法:

    public static int cal(List<String> list) {
        //创建一个栈
        Stack<String> stack = new Stack<String>();
        int res = 0;
        //遍历 list
        for (String s : list) {
            //这里使用正则表达式取出来数
            if (s.matches("\\d+")) {//如果是多个数字,直接入栈
                stack.push(s);
            } else {
                //如果取出的不是数字,需要弹出两个数字,进行运算,将运算结果,继续入栈操作
                int num2 = Integer.parseInt(stack.pop());
                int num1 = Integer.parseInt(stack.pop());
                if (s.equals("+")) {
                    res = num1 + num2;
                } else if (s.equals("-")) {
                    res = num1 - num2;
                } else if (s.equals("*")) {
                    res = num1 * num2;
                } else if (s.equals("/")) {
                    res = num1 / num2;
                } else {
                    throw new RuntimeException("您输入的运算符有误!");
                }
                stack.push("" + res);
            }
        }
        return Integer.parseInt(stack.pop());
    }

测试类:

public static void main(String[] args) {
        //先定义逆波兰表达式
        //(3+4)*5-6 ==> 3 4 + 5 * 6 -
        //说明为了方便,逆波兰表达式的 数字和字符使用空格隔开
        String Expression = "(10+2)*5-6*2";

        /** 思路
         *  1. 先将 " 3 4 + 5 * 6 - " => 放到ArrayList中
         *  2. 将ArrayList 传递给一个方法,遍历ArrayList 配合栈 完成计算
         */

        //得到一个后缀表达式
        List<String> list = toIndixExpressionList(Expression);

        System.out.println("运算表达式为:" + list);

        //将中缀表达式转化为后缀表达式
        List<String> suffixExpression = parseSuffixExpressionList(list);
        System.out.println("后缀表达式为: "+suffixExpression);


        //现在进行运算
        System.out.println(list + " = " + cal(suffixExpression));
    }

 控制台输出:

最近更新

  1. TCP协议是安全的吗?

    2023-12-23 04:52:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-23 04:52:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-23 04:52:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-23 04:52:01       20 阅读

热门阅读

  1. 网络安全学习-NTFS安全权限、文件共享

    2023-12-23 04:52:01       38 阅读
  2. export default

    2023-12-23 04:52:01       33 阅读
  3. 基于猫群算法优化的BP神经网络实现数据预测

    2023-12-23 04:52:01       39 阅读
  4. 使用arthas排查请求超时问题

    2023-12-23 04:52:01       40 阅读
  5. Android Native Hook 深入理解PLT hook

    2023-12-23 04:52:01       42 阅读
  6. C# 获取本机IP地址的方法

    2023-12-23 04:52:01       44 阅读
  7. vue3 常用函数\\组件传值

    2023-12-23 04:52:01       39 阅读
  8. 图像ISP处理——自动曝光AE算法

    2023-12-23 04:52:01       135 阅读
  9. [AIGC] 区块链简介

    2023-12-23 04:52:01       44 阅读
  10. 终止 MATLAB 程序的方法

    2023-12-23 04:52:01       41 阅读
  11. Centos9(Stream)配置Let‘s Encrypt (免费https证书)

    2023-12-23 04:52:01       48 阅读
  12. Linux: dev: gcc: Instrumentation 程序的检测仪表/手段

    2023-12-23 04:52:01       48 阅读