前缀、中缀、后缀表达式及逆波兰计算器实现

1.前缀表达式(波兰表达式)

1.1 介绍

  • 前缀表达式又称波兰式,前缀表达式的运算符位于操作数之前。
  • 举例说明:(3+4)*5-6 对应的前缀表达式就是 - * + 3 4 5 6

1.2 前缀表达式的计算机求值

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

例如 (3+4)×5-6 对应的前缀表达式就是 - × + 3 4 5 6 , 针对前缀表达式求值步骤如下:

  1. 从右至左扫描,将6、5、4、3压入堆栈。
  2. 遇到+运算符,因此弹出3和4(3为栈顶元素,4为次顶元素),计算出3+4的值,得7,再将7入栈。
  3. 接下来是×运算符,因此弹出7和5,计算出7×5=35,将35入栈。
  4. 最后是-运算符,计算出35-6的值(先弹出的 - 后弹出的),即29,由此得出最终结果。

2.中缀表达式

  • 中缀表达式就是常见的运算表达式,如(3+4)*5-6
  • 中缀表达式的求值是我们人最熟悉的,但是对计算机说却不好操作(前面我们讲的案例就能看出这个问题)因此,在计算结果时,往往会将中缀表达式转成其它表达式来操作(一般是转成后缀表达式)。

3.后缀表达式(逆波兰表达式)

3.1 介绍

  • 后缀表达式又称逆波兰表达式,与前缀表达式相似,只是运算符位于操作数之后
  • 举例说明: (3+4)×5-6 对应的后缀表达式就是 3 4 + 5 × 6 –

在这里插入图片描述

3.2 后缀表达式的计算机求值

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

例如: (3+4)×5-6 对应的后缀表达式就是 3 4 + 5 × 6 -, 针对后缀表达式求值步骤如下:

  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,由此得出最终结果。

4.逆波兰计算器

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

  • 输入一个逆波兰表达式(后缀表达式),使用栈(Stack), 计算其结果。
  • 支持小括号和多位数整数,因为这里我们主要讲的是数据结构,因此计算器进行简化,只支持对整数的计算。
/**
 * @ClassName PolandNotation
 * @author: shouanzh
 * @Description 逆波兰计算器
 * @date 2022/5/1 16:20
 */
public class PolandNotation {

    public static void main(String[] args) {

        // 定义一个逆波兰表达式
        // (3+4)*5-6 => 3 4 + 5 * 6 -
        // 为了方便 数字和符号 用 空格 隔开
        String suffixExpression = "3 4 + 5 * 6 -";

        // 1.先将 "3 4 + 5 * 6 -" 放入ArrayList中去
        // 2.将ArrayList传递给一个方法,配合栈完成计算
        List<String> rpnList = getListString(suffixExpression);
        System.out.println("rpnList:" + rpnList);
        int calculate = calculate(rpnList);
        System.out.println("计算结果是 = " + calculate);

    }


    /**
     * 将逆波兰表达式的数据和运算符依次放到ArrayList中
     * @param suffixExpression 逆波兰表达式
     * @return ArrayList
     */
    public static List<String> getListString(String suffixExpression) {
        // 将suffixExpression分割
        String[] split = suffixExpression.split(" ");

        List<String> list = new ArrayList<>();

        for (String element : split) {
            list.add(element);
        }

        return list;
    }


    /**
     * 计算逆波兰表达式最终结果  3 4 + 5 * 6 -
     * 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,由此得出最终结果。
     * @param rpnList 数据和运算符
     * @return 计算结果
     */
    public static int calculate(List<String> rpnList) {

        // 创建一个栈即可
        Stack<String> stack = new Stack<>();

        // 遍历链表
        for (String element : rpnList){
            // 使用正则表达式来取出数,匹配多位数
            if (element.matches("\\d+")) {
                // 入栈
                stack.push(element);
            } else {
                // pop出两个数,并进行运算再入栈
                int num2 = Integer.parseInt(stack.pop());
                int num1 = Integer.parseInt(stack.pop());
                int res; // 计算结果
                switch (element) {
                    case "+":
                        res = num1 + num2;
                        break;
                    case "-":
                        res = num1 - num2; // 后弹出的 - 先弹出的
                        break;
                    case "*":
                        res = num1 * num2;
                        break;
                    case "/":
                        res = num1 / num2;
                        break;
                    default:
                        throw new RuntimeException("运算符有误");
                }
                // 把res 入栈
                stack.push(res + "");
            }
        }
        return Integer.parseInt(stack.pop());
    }
}

5.中缀表达式转换为后缀表达式

后缀表达式适合计算式进行运算,但是人却不太容易写出来,尤其是表达式很长的情况下,因此在开发中,我们需要将中缀表达式转成后缀表达式。

5.1 思路分析

举例:1+((2+3)×4)-5 转 “1 2 3 + 4 × + 5 –”
在这里插入图片描述

具体步骤如下:

  1. 初始化两个栈:运算符栈s1和储存中间结果的栈s2;

  2. 从左至右扫描中缀表达式;

  3. 遇到操作数时,将其压入s2;

  4. 遇到运算符时,比较其与s1栈顶运算符的优先级:

    • 如果s1为空,或栈顶运算符为左括号“(”,则直接将此运算符入栈;
    • 否则,若优先级比栈顶运算符的高,也将运算符压入s1;
    • 否则,将s1栈顶的运算符弹出并压入到s2中,再次转到(4.1步骤)与s1中新的栈顶运算符相比;
  5. 遇到括号时:

    • 如果是左括号“(”,则直接压入s1;
    • 如果是右括号“)”,则依次弹出s1栈顶的运算符,并压入s2,直到遇到左括号为止,此时将这一对括号丢弃;
  6. 重复步骤2至5,直到表达式的最右边;

  7. 将s1中剩余的运算符依次弹出并压入s2;

  8. 依次弹出s2中的元素并输出,结果的逆序即为中缀表达式对应的后缀表达式

5.2 代码实现

/**
 * @ClassName FolandNotation
 * @author: shouanzh
 * @Description 中缀转后缀
 * @date 2022/5/1 20:20
 */
public class FolandNotation {

    public static void main(String[] args) {

        // 将一个中缀表达式转成后缀表达式
        // 1、1+((2+3)×4)-5 => 转成 1 2 3 + 4 × + 5 –
        // 2、因为直接对str 进行操作,不方便,因此 先将 "1+((2+3)×4)-5" =》 中缀的表达式对应的List
        //    即  1+((2+3)×4)-5 =》 ArrayList [1,+,(,(,2,+,3,),*,4,),-,5]
        String str = "1+((2+3)*4)-5";
        List<String> list = toInfixExpressionList(str);
        System.out.println("中缀表达式对应的List=" + list); // ArrayList [1,+,(,(,2,+,3,),*,4,),-,5]
        // 3、将得到的中缀表达式对应的List => 后缀表达式对应的List
        List<String> suffixExpressionList = parseSuffixExpressionList(list);
        System.out.println("后缀表达式对应的List=" + suffixExpressionList); // ArrayList [1, 2, 3, +, 4, *, +, 5, -]
        System.out.printf("expression=%d", calculate(suffixExpressionList));
    }

    /**
     * 将中缀表达式字符串转成List
     * @param s 中缀表达式
     * @return
     */
    public static List<String> toInfixExpressionList(String s) {
        // 定义一个List,存放中缀表达式
        List<String> ls = new ArrayList<>();
        // 定义一个指针,用于遍历
        int index = 0;
        // 拼接多位数
        StringBuilder str;
        // 存储每次遍历的字符
        char c;
        do {
            // 若 c 不是数字,则加入 ls集合
            if ((c = s.charAt(index)) > '9' || (c = s.charAt(index)) < '0') {
                ls.add("" + c);
                // 指针后移
                index++;
            } else {
                // 如果是一个数字,还得考虑多位数与否
                // 先将str 置成"",每次拼接前先清空上次的记录
                str = new StringBuilder();
                // 如果是数字,并且表达式内还有值
                while (index < s.length() && s.charAt(index) >= '0' && (c = s.charAt(index)) <= '9') {
                    str.append(c);// 拼接多位数
                    index++;
                }
                ls.add(str.toString());
            }
        } while (index < s.length());
        return ls;
    }

    /**
     * 中缀list 转 后缀List
     * ArrayList [1,+,(,(,2,+,3,),*,4,),-,5] =》 ArrayList [1,2,3,+,4,*,+,5,–]
     * @param ls 中缀list
     * @return 后缀List
     */
    public static List<String> parseSuffixExpressionList(List<String> ls) {
        // 原本定义两个栈,一个符号栈S1,一个存储中间计算和最终结果的栈S2
        // 说明,栈S2 因为需要全程是没有pop出的,最终还得逆序输出一次,就改为 list
        Stack<String> s1 = new Stack<>();// 符号栈
        List<String> s2 = new ArrayList<>();// 原定的s2

        // 遍历中缀 list
        for (String item : ls) {
            // 若是一个数字(包括多位数和1-9),加入s2
            if (item.matches("\\d+")) {
                s2.add(item);
            } else if ("(".equals(item)) {
                s1.push(item);
            } else if (")".equals(item)) {
                // 如果是右括号“)”,则依次弹出s1栈顶的运算符,并压入s2,
                // 直到遇到左括号为止,此时将这一对括号及其内的所有数字和运算符丢弃
                while (s1.size() != 0 && !s1.peek().equals("(")) {
                    s2.add(s1.pop());
                }
                s1.pop();// 将 ( 弹出 s1栈, 消除小括号
            } else {
                // 当item的优先级小于等于s1栈顶运算符, 将s1栈顶的运算符弹出并加入到s2中,
                // 再次转到(4.1)与s1中新的栈顶运算符相比较
                while (s1.size() != 0 && !"(".equals(s1.peek()) && Operation.getValue(s1.peek()) >= Operation.getValue(item)) {
                    s2.add(s1.pop());
                }
                // 将item压栈
                s1.push(item);
            }
        }

        // 将s1中剩余的最后一个运算符弹出并加入s2
        while (s1.size() != 0) {
            s2.add(s1.pop());
        }
        // 因为是存放到List, 因此按顺序输出就是对应的后缀表达式对应的List
        return s2;
    }

    /**
     * 对逆波兰表达式进行运算
     * @param ls 后缀表达式
     * @return
     */
    public static int calculate(List<String> ls) {
        // 创建一个栈,用于存储依次弹出计算
        Stack<String> 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;
                switch (item) {
                    case "+":
                        res = num1 + num2;
                        break;
                    case "-":
                        res = num1 - num2;
                        break;
                    case "*":
                        res = num1 * num2;
                        break;
                    case "/":
                        res = num1 / num2;
                        break;
                    default:
                        throw new RuntimeException("运算符有误");
                }
                // 运算后入栈
                stack.push("" + res);
            }
        }
        // 最后留在stack中的数据是运算结果
        return Integer.parseInt(stack.pop());
    }

}

// 编写一个类 Operation 可以返回一个运算符 对应的优先级
class Operation {
    private static final int ADD = 1;
    private static final int SUB = 1;
    private static final int MUL = 2;
    private static final 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("不存在该运算符" + operation);
                break;
        }
        return result;
    }
}

运行结果

中缀表达式对应的List=[1, +, (, (, 2, +, 3, ), *, 4, ), -, 5]
后缀表达式对应的List=[1, 2, 3, +, 4, *, +, 5, -]
expression=16

6.完整版逆波兰计算器

  • 支持 + - * / ( )
  • 多位数,支持小数
  • 兼容处理, 过滤任何空白字符,包括空格、制表符、换页符
/**
 * 完整版逆波兰计算器
 */
public class ReversePolishMultiCalc {

    /**
     * 匹配 + - * / ( ) 运算符
     */
    static final String SYMBOL = "\\+|-|\\*|/|\\(|\\)";

    static final String LEFT = "(";
    static final String RIGHT = ")";
    static final String ADD = "+";
    static final String MINUS = "-";
    static final String TIMES = "*";
    static final String DIVISION = "/";

    /**
     * 加減 + -
     */
    static final int LEVEL_01 = 1;
    /**
     * 乘除 * /
     */
    static final int LEVEL_02 = 2;

    /**
     * 括号
     */
    static final int LEVEL_HIGH = Integer.MAX_VALUE;


    static Stack<String> stack = new Stack<>();
    static List<String> data = Collections.synchronizedList(new ArrayList<>());

    /**
     * 去除所有空白符
     * @param s
     * @return
     */
    public static String replaceAllBlank(String s) {
        //  \\s+ 匹配任何空白字符,包括空格、制表符、换页符等等, 等价于[ \f\n\r\t\v]
        return s.replaceAll("\\s+", "");
    }

    /**
     * 判断是不是数字 int double long float
     * @param s
     * @return
     */
    public static boolean isNumber(String s) {
        Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$");
        return pattern.matcher(s).matches();
    }

    /**
     * 判断是不是运算符
     * @param s
     * @return
     */
    public static boolean isSymbol(String s) {
        return s.matches(SYMBOL);
    }

    /**
     * 匹配运算等级
     * @param s
     * @return
     */
    public static int calcLevel(String s) {
        if ("+".equals(s) || "-".equals(s)) {
            return LEVEL_01;
        } else if ("*".equals(s) || "/".equals(s)) {
            return LEVEL_02;
        }
        return LEVEL_HIGH;
    }

    /**
     * 匹配
     * @param s
     */
    public static List<String> doMatch(String s) {
        if (s == null || "".equals(s.trim())){
            throw new RuntimeException("data is empty");
        }

        if (!isNumber(s.charAt(0) + "")) {
            throw new RuntimeException("data illeagle,start not with a number");
        }

        s = replaceAllBlank(s);

        String each;
        int start = 0;

        for (int i = 0; i < s.length(); i++) {
            if (isSymbol(s.charAt(i) + "")) {
                each = s.charAt(i) + "";
                // 栈为空,(操作符,或者 操作符优先级大于栈顶优先级 && 操作符优先级不是( )的优先级 及是 ) 不能直接入栈
                if (stack.isEmpty() || LEFT.equals(each)
                        || ((calcLevel(each) > calcLevel(stack.peek())) && calcLevel(each) < LEVEL_HIGH)) {
                    stack.push(each);
                } else if (!stack.isEmpty() && calcLevel(each) <= calcLevel(stack.peek())) {
                    // 栈非空,操作符优先级小于等于栈顶优先级时出栈入列,直到栈为空,或者遇到了(,最后操作符入栈
                    while (!stack.isEmpty() && calcLevel(each) <= calcLevel(stack.peek())) {
                        if (calcLevel(stack.peek()) == LEVEL_HIGH) {
                            break;
                        }
                        data.add(stack.pop());
                    }
                    stack.push(each);
                } else if (RIGHT.equals(each)) {
                    //  ) 操作符,依次出栈入列直到空栈或者遇到了第一个)操作符,此时)出栈
                    while (!stack.isEmpty() && LEVEL_HIGH >= calcLevel(stack.peek())) {
                        if (LEVEL_HIGH == calcLevel(stack.peek())) {
                            stack.pop();
                            break;
                        }
                        data.add(stack.pop());
                    }
                }
                start = i; // 前一个运算符的位置
            } else if (i == s.length() - 1 || isSymbol(s.charAt(i + 1) + "")) {
                each = start == 0 ? s.substring(start, i + 1) : s.substring(start + 1, i + 1);
                if (isNumber(each)) {
                    data.add(each);
                    continue;
                }
                throw new RuntimeException("data not match number");
            }
        }
        // 如果栈里还有元素,此时元素需要依次出栈入列,可以想象栈里剩下栈顶为/,栈底为+,应该依次出栈入列,可以直接翻转整个stack 添加到队列
        Collections.reverse(stack);
        data.addAll(new ArrayList<>(stack));

        System.out.println(data);
        return data;
    }

    /**
     * 算出结果
     * @param list
     * @return
     */
    public static Double doCalc(List<String> list) {
        double d = 0d;
        if (list == null || list.isEmpty()) {
            return null;
        }
        if (list.size() == 1) {
            System.out.println(list);
            d = Double.parseDouble(list.get(0));
            return d;
        }
        ArrayList<String> list1 = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            list1.add(list.get(i));
            if (isSymbol(list.get(i))) {
                Double d1 = doTheMath(list.get(i - 2), list.get(i - 1), list.get(i));
                list1.remove(i);
                list1.remove(i - 1);
                list1.set(i - 2, d1 + "");
                list1.addAll(list.subList(i + 1, list.size()));
                break;
            }
        }
        doCalc(list1);
        return d;
    }

    /**
     * 运算
     * @param s1
     * @param s2
     * @param symbol
     * @return
     */
    public static Double doTheMath(String s1, String s2, String symbol) {
        Double result;
        switch (symbol) {
            case ADD:
                result = Double.parseDouble(s1) + Double.parseDouble(s2);
                break;
            case MINUS:
                result = Double.parseDouble(s1) - Double.parseDouble(s2);
                break;
            case TIMES:
                result = Double.parseDouble(s1) * Double.parseDouble(s2);
                break;
            case DIVISION:
                result = Double.parseDouble(s1) / Double.parseDouble(s2);
                break;
            default:
                result = null;
        }
        return result;

    }

    public static void main(String[] args) {
        String math = "99.1+(3-1)*3+10/2";
        try {
            doCalc(doMatch(math));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

运行结果

[99.1, 3, 1, -, 3, *, +, 10, 2, /, +]
[110.1]

🧐

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值