Postfix infix expression turn, Java realization

Infix expression is a general representation of arithmetic or logical formulas, the conjugated form of the operator is in the middle of the operand (Example: 3 + 4), infix expressions are often used in an arithmetic representation.

Prefix expression (example: +34) or postfix notation (example: 34+) compared to infix expression does not easily parsed by computers, but many programs still use the language, because it is consistent with widespread usage.

E.g:

Example 1: 8 + 4--6 2 * is represented by the postfix:

8 4 + 6 2 * -

Example 2: 2 * (3 + 5) + 7 / 1--4 postfix expression is represented by:

* 235 + 71 / + 4 - [Encyclopedia Solutions *** 35 * 71 + 2/4 - +] is wrong, although numerically correct result, but generally does not change

- Transfer from Baidu Encyclopedia

Infix turn suffix is ​​how the Internet has transformed explain in great detail, this text does not go into details.

If you do not understand the students can see: https://www.bilibili.com/video/av18586085/?p=20

Code:

public class Main {

    public static void main(String[] args) {

        Stack<String> stack = new Stack<>(); // new一个栈
        String[] array = "2 * ( 9 + 6 / 3 - 5 ) + 4".split(" "); // 中缀表达式
        List<String> list = new LinkedList<>(); // list存储后缀表达式

        for (String s : array) {
            if (isNumber(s)) {
                // 数字直接输出
                list.add(s);
            } else {
                // 1.根据当前读到的运算符判断是否需要弹出
                // 1.1 如果栈当前不为空且s不是"("且栈顶不是"(",则判断运算符
                // 反之:栈为空栈或当前字符为"("或栈顶是"(",则s直接入栈
                if (stack.size() > 0 && !"(".equals(s) && !"(".equals(stack.peek())) {
                    // 如果是")",将栈顶至第一个"("弹出
                    String top = null;
                    if (")".equals(s)) {
                        while (!"(".equals(top = stack.pop())) {
                            list.add(top);
                        }
                    } else {
                        // 如果是运算符,比较优先级,将优先级大于等于当前s的都弹出
                        while (stack.size() > 0 && compare(top = stack.peek(), s) > -1) {
                            list.add(top);
                            stack.pop();
                        }
                    }
                }
                // 2.把当前运算符压入栈
                if (!")".equals(s)) {
                    stack.push(s);
                }
            }
        }
        // 3.最后栈中剩的一定是最后一个运算符和比最后一个运算符优先级小的运算符,否则之前就已经弹出了
        while (stack.size() > 0) {
            list.add(stack.pop());
        }
        // 4.输出后缀表达式
        for (String s : list) {
            System.out.print(" " + s);
        }
        System.out.println();
    }

    // 比较两个运算符,返回正数则a优先级大于b,负数则a优先级小于b
    private static int compare(String a, String b) {
        // "("的优先级比任何运算符都小
        if ("(".equals(a)) {
            return -99999;
        }
        if ("(".equals(b)) {
            return 99999; // 本实现中b不会出现这种情况
        }
        int aScore = "+".equals(a) || "-".equals(a) ? 0 : 1;
        int bScore = "+".equals(b) || "-".equals(b) ? 0 : 1;
        return aScore - bScore;
    }
    
    // 是数字则返回true
    private static isNumber(String s){
        return "0123456789".contains(s);
    }

}

That my own little understanding:

  1. Postfix expression 优先级是众生平等, the order of operations is from left to right, even before the addition and subtraction, multiplication and division, addition and subtraction also need to be considered

  2. Because numerical order postfix expression is not going to change 仅运算符变位, so no need to fully comply with human intuitive understanding of multiplication and division or the number in parentheses to the front (just like the wrong solution, like Baidu Encyclopedia), as long as a 运算符is previously calculated the results of the two elements can be

  3. So it is necessary to ensure that all operators are into a stack, so we can guarantee a higher priority, first-out stack, then put the operator stack, do not worry appeared Example 1 +first pop-up *after pop-up will not go wrong, you can this way:

    Because this is a binary operation, it is determined *when the stack +has a stack, the stack and it is because -that the foregoing description has been at least 3 digits, then even do a +calculation just in front of the first two figures, but *now only before you need one number, so the +operation will not affect *the desired number, but if +immediately after is that *, *when the stack if you do a +will to *affect the desired number, so +can not pop

  4. In the expression without parentheses, the multiplication and division takes precedence over addition and subtraction nothing to say, but also to calculate multiplication and division from left to right, the equivalent 同级运算符也是有优先级的, will be a first output in front of multiplication and division, multiplication and division, it is time to pop this operator than this 优先级高的或相同优先级are pop

  5. Parenthesis is a bug, equivalent 被括号包围的运算符优先级翻倍, so even the addition and subtraction in parentheses much higher than multiplication and division priority outside the parentheses, then how to reflect the priorities doubled in the code, could not let the b doubling compare methods, then put (the set to the lowest priority, so that (in any case will not pop up, and so it )appears like

Guess you like

Origin www.cnblogs.com/n031/p/11291842.html