带你走进Java数据结构与算法(八)

79 阅读3分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第二十天,点击查看活动详情

前言:上文学习了 逆波兰计算器,今天带领大家了解中缀转后缀~

中缀转后缀

将这个中缀表达式:1 + (( 2 + 3) × 4 ) - 5 ===》后缀表达式

分析步骤

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

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

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

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

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

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

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

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

package com.stack;
​
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
​
/**
 * @author Kcs 2022/8/13
 */
public class PolandNotation {
    public static void main(String[] args) {
​
        // 中缀 ===》后缀
        // 1 + (( 2 + 3) * 4 ) - 5 ===》1 2 3 + 4 * + 5 –
        String expression = "1+((2+3)*4)-5";
        List<String> infixExpressionList = toInfixExpressionList(expression);
        System.out.println("中缀表达式:" + infixExpressionList);
​
        List<String> suffixExpressionList = parseSuffixExpressionList(infixExpressionList);
        System.out.println("后缀表达式:" + suffixExpressionList);
​
        System.out.println("后缀表达式的结果 = " + calculate(suffixExpressionList));
    /**
     * 将中缀表达式转为List 上面的中缀表达式存入List得到的结果:[1, +, (, (, 2, +, 3, ), ×, 4, ), -, 5]
     */
    public static List<String> toInfixExpressionList(String s) {
        //存放中缀表达式内容
        ArrayList<String> list = new ArrayList<>();
        //定义指针,遍历中缀表达式
        int i = 0;
        //多位拼接
        String str;
        char c;
        do {
            //c为非数字
            if ((c = s.charAt(i)) < 48 || (c = s.charAt(i)) > 57) {
                list.add("" + c);
                //后移
                i++;
            } else {
                //多位数
                str = "";
                while (i < s.length() && (c = s.charAt(i)) >= 48 && (c = s.charAt(i)) <= 57) {
                    str += c;
                    i++;
                }
                list.add(str);
            }
        } while (i < s.length());
        return list;
    }
​
​
    /**
     * 将得到的中缀表达式转换成 后缀表达式
     */
    public static List<String> parseSuffixExpressionList(List<String> list) {
        // 定义栈 符号栈
        Stack<String> s1 = new Stack<String>();
        //存储中间结果的栈,使用List方便操作
        List<String> s2 = new ArrayList<String>();
​
        //遍历list
        for (String item : list) {
            //为数,入s2
            if (item.matches("\d+")) {
                s2.add(item);
            } else if (item.equals("(")) {
                s1.push(item);
            } else if (item.equals(")")) {
                //依次弹出s1栈顶的运算符,并压入s2,直到遇到左括号为止,此时将这一对括号丢弃
                while (!s1.peek().equals("(")) {
                    s2.add(s1.pop());
                }
                //将左括号弹出,消除小括号
                s1.pop();
            } else {
                //item的优先级比s1栈顶的优先级小,将s1栈顶的运算符弹出并压入到s2中,再次转到与s1中新的栈顶运算符相比较
                while (s1.size() != 0 && 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,正常输入就是逆波兰表达式
        return s2;
    }
​
​
    /**
     * 表达式 存入ArrayList中
     * @param suffixExpression
     * @return String[]
     */
    public static List<String> getListString(String suffixExpression) {
        //将表达式分割
        String[] spilt = suffixExpression.split(" ");
        List<String> list = new ArrayList<String>();
        for (String ele : spilt) {
            list.add(ele);
        }
        return list;
    }
​
    // 逆波兰表达式的运算
    public static int calculate(List<String> ls) {
​
        //创建给栈,只需要一个栈
        Stack<String> stack = new Stack<String>();
​
        // 遍历 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 = 0;
                if (item.equals("+")) {
                    res = num1 + num2;
                } else if (item.equals("-")) {
                    //用后出栈的减去先出栈的
                    res = num1 - num2;
                } else if (item.equals("*")) {
                    res = num1 * num2;
                } else if (item.equals("/")) {
                    //用后出栈的 除以 先出栈的
                    res = num1 / num2;
                } else {
                    throw new RuntimeException("运算符有问题,不属于四则运算符号");
                }
                stack.push("" + res);
            }
        }
        //最后留在栈里的数据是运算结果
        return Integer.parseInt(stack.pop());
    }
}
​
​
/**
 * 优先级高低,返回运算符对应的优先级
 */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;
    }
}