Infix expression to suffix expression, Java implementation

Keywords: PHP Programming less

Infix expression is a general arithmetic or logical formula representation. Operators are in the middle of operands in the form of infix (example: 3+4). Infix expression is a common arithmetic representation.

Compared with prefix expressions (example: +34) or suffix expressions (example: 34+), infix expressions are not easily parsed by computers, but are still used by many programming languages because they conform to common usage.

For example:

Example 1:8 + 4 - 6 * 2 is expressed as a suffix expression:

8 4 + 6 2 * -

Example 2:2 * (3 + 5) + 7 / 1 - 4 is expressed as a suffix expression:

The solution of Encyclopedia [3 5 + 2 * 7 1 / 4 - *** is wrong, although the result is correct, the number order generally does not change

- From Baidu Encyclopedia

How suffix-to-suffix converts has been explained in detail on the Web, and is not covered in this article.

If you don't understand your classmates, you can see: https://www.bilibili.com/video/av18586085/?p=20

Code implementation:

public class Main {

    public static void main(String[] args) {

        Stack<String> stack = new Stack<>(); // new a stack
        String[] array = "2 * ( 9 + 6 / 3 - 5 ) + 4".split(" "); // Infix expression
        List<String> list = new LinkedList<>(); // list stores suffix expressions

        for (String s : array) {
            if (isNumber(s)) {
                // Digital Direct Output
                list.add(s);
            } else {
                // 1. Determine whether pop-ups are required based on the operators currently read
                // 1.1 Judgement operator if the stack is not currently empty and s is not'('and the top of the stack is not'('
                // Conversely, if the stack is empty or the current character is'('or if the top of the stack is'(', s goes directly to the stack
                if (stack.size() > 0 && !"(".equals(s) && !"(".equals(stack.peek())) {
                    // If it is "), pop up the top of the stack to the first"("
                    String top = null;
                    if (")".equals(s)) {
                        while (!"(".equals(top = stack.pop())) {
                            list.add(top);
                        }
                    } else {
                        // If it is an operator, compare priorities and eject all that have priority greater than or equal to the current s
                        while (stack.size() > 0 && compare(top = stack.peek(), s) > -1) {
                            list.add(top);
                            stack.pop();
                        }
                    }
                }
                // 2. Push the current operator on the stack
                if (!")".equals(s)) {
                    stack.push(s);
                }
            }
        }
        // 3. The last remaining operator on the stack must be the last one and one that has a lower priority than the last one, otherwise it has already popped up before
        while (stack.size() > 0) {
            list.add(stack.pop());
        }
        // 4. Output suffix expression
        for (String s : list) {
            System.out.print(" " + s);
        }
        System.out.println();
    }

    // Compare two operators and return positive numbers with a priority greater than b and negative numbers with a priority less than b
    private static int compare(String a, String b) {
        // '('has a lower precedence than any operator
        if ("(".equals(a)) {
            return -99999;
        }
        if ("(".equals(b)) {
            return 99999; // This will not happen in this implementation
        }
        int aScore = "+".equals(a) || "-".equals(a) ? 0 : 1;
        int bScore = "+".equals(b) || "-".equals(b) ? 0 : 1;
        return aScore - bScore;
    }
    
    // Is a number then returns true
    private static isNumber(String s){
        return "0123456789".contains(s);
    }

}

Tell me a little about my own understanding:

  1. Suffix expressions have the same priority as all living beings, and the order of operation is from left to right. Even before multiplication and division, addition and subtraction must be calculated first.

  2. Because the numeric order of the suffix expression will not change, only the operator dislocation, it is not necessary to fully follow the intuitive understanding of people to multiply and divide or put the numbers in parentheses in front (as Baidu Encyclopedia did in the wrong way), as long as one operator is the result of computing the first two elements.

  3. So you need to make sure that all operators are on the stack once, so that you can make sure that the operator with the highest priority is on the stack first, and then put the operator on the stack this time. You don't have to worry if there will be any errors in example 1 + pop-up first* and then pop-up. Understand this:

    Because this is a binary operation, when you decide * on the stack, + has already left the stack, and it goes out because -, that means there are at least three digits in front of it, then even if you do a + operation, it will only be the first two digits before it, and * now only needs the first one digits, so this + operation will not affect the number required by * but if it is at +Next to that is *, * If you do a + once on the stack, it will affect the number that * needs, so + cannot go out of the stack

  4. In parentheses-free expressions, it is nothing to say that multiplication and division take precedence over addition and subtraction, but multiplication and division are also calculated from left to right, which is equivalent to the priority of sibling operators. Multiplication and division before a multiplication and division are sure to output first, so this operator must take precedence over or be the same superiority when it comes out of the stack.All the first ones pop up

  5. Parentheses are a bug that doubles the priority of an operator surrounded by parentheses, so even if the addition or subtraction within parentheses is more preferred than the multiplication except for parentheses, then how to represent a double of the priority in the code, naturally B cannot be doubled in the compare method, then (the priority is set to the lowest, no matter how (e.g., b) the priority is doubled in the comparison methodNothing will pop up, just let it wait)

Posted by gernot on Fri, 02 Aug 2019 11:49:14 -0700