Infix expression to suffix expression (Java)

Infix expression to suffix expression (Java)

Blog description

The information involved in this article comes from Internet collation and personal summary, which means personal learning and experience summary. If there is any infringement, please contact me to delete, thank you!

step

  1. Two stacks are initialized: operator stack s1 and stack s2 storing intermediate results

  2. Scan infix expression from left to right

  3. When an operand is encountered, press s2

  4. When an operator is encountered, compare its priority with s1 stack top operator:

    • If s1 is empty, or the top of stack operator is left parenthesis "(", the operator will be directly pushed into the stack
    • Otherwise, if the priority is higher than the stack top operator, the operator is also pressed into s1;
    • Otherwise, pop up the operator at the top of s1 stack and press it into s2, and turn to (4-1) again to compare with the new operator at the top of s1 stack;
  5. When parentheses are encountered:

    • If it is the left bracket "(", press s1 directly
    • If it is a right parenthesis ")", the operators at the top of s1 stack will pop up in turn, and press s2 until the left parenthesis is encountered. At this time, this pair of parentheses will be discarded
  6. Repeat steps 2 through 5 until the far right of the expression

  7. Pop up the remaining operators in s1 and press them into s2

  8. Pop out the elements in s2 in turn and output. The reverse order of the result is the suffix expression corresponding to infix expression

case

The process of converting infix expression "1 + ((2 + 3) × 4) - 5" to suffix expression is as follows

So the result is: "123 + 4 × + 5 –"

code

package stack;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author guizimo
 * @date 2020/4/6 12:25 afternoon
 */
public class PolandNotation {
    public static void main(String[] args) {
        //expression
        String suffixExpression = "1+((2+3)*4)-5";
        //List corresponding to infix expression
        System.out.println("Infix expression corresponding to List");
        List<String> infixExpressionList = toInfixExpressionList(suffixExpression);
        System.out.println(infixExpressionList);
        //List corresponding to suffix expression
        System.out.println("Corresponding to suffix expression List");
        List<String> suffixExpressionList = parseSuffixExpressionList(infixExpressionList);
        System.out.println(suffixExpressionList);

        //Calculate inverse Polish expression
        System.out.printf("suffixExpression=%d", calculate(suffixExpressionList));

    }

    public static List<String> parseSuffixExpressionList(List<String> ls) {
        //Define two stacks
        Stack<String> s1 = new Stack<String>();  //Symbol stack
        List<String> s2 = new ArrayList<String>();  //result

        for (String item : ls) {
            //If it's a number
            if (item.matches("\\d+")) {
                s2.add(item);
            } else if (item.equals("(")) {
                s1.push(item);
            } else if (item.equals(")")) {
                while (!s1.peek().equals("(")) {
                    s2.add(s1.pop());
                }
                s1.pop();
            } else {
                while (s1.size() != 0 && Operation.getValue(s1.peek()) >= Operation.getValue(item)) {
                    s2.add(s1.pop());
                }
                s1.push(item);
            }
        }
        while (s1.size() != 0) {
            s2.add(s1.pop());
        }
        return s2;
    }

    //Convert infix expression to list
    public static List<String> toInfixExpressionList(String s) {
        List<String> ls = new ArrayList<String>();
        int i = 0;
        String str;  //Number of bits
        char c;
        do {
            //Nonnumeric
            if ((c = s.charAt(i)) < 48 || (c = s.charAt(i)) > 57) {
                ls.add("" + c);
                i++;
            } else { //Number, but considering the number of bits
                str = "";
                while (i < s.length() && (c = s.charAt(i)) >= 48 && (c = s.charAt(i)) <= 57) {
                    str += c;
                    i++;
                }
                ls.add(str);
            }
        } while (i < s.length());
        return ls;
    }

    //Complete the calculation of the inverse Polish expression
    public static int calculate(List<String> ls) {
        Stack<String> stack = new Stack<>();
        for (String item : ls) {
            //Using regular expressions
            if (item.matches("\\d+")) {  //Match multiple bits
                //Push 
                stack.push(item);
            } else {
                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("Problem with operator");
                }
                //Stack results
                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("non-existent");
                break;
        }
        return result;
    }
}

thank

Shangsilicon Valley

Omnipotent network

And the industrious self
Pay attention to the official account: get back to the information, get more information, and have a longer learning plan.

Tags: Java network

Posted on Thu, 25 Jun 2020 05:14:41 -0400 by jayjay960