Java implements a suffix expression to a suffix expression and evaluates the result

Stack

Infix expressions are expressions such as a(b-c)+d*, which we usually write. It is difficult for computers to handle them correctly if they are in the usual logical order of processing, because there is priority among operators, the priority of parentheses is higher than multiplication and division, and the priority of multiplication and division is higher than addition and subtraction. This is elementary school knowledge.
If you take advantage of the First In Last Out feature of the stack, you can convert a suffix expression to a suffix expression.
The suffix expression does not contain parentheses, and the operator is placed after two objects. All calculations are performed from left to right in the order in which the operators appear (regardless of operator precedence rules, such as: (2 + 1) * 3, that is, 2 1 + 3 *

thinking

  1. Read in Characters
  2. If the character read in is an operator, the stack, and if it is an operand, the output
  3. If the operator priority read in is lower than the top element of the stack, the stack operator pops up until it encounters an operator with a lower priority than the operator read in.Left parenthesis (in special cases, read as high priority, pop-up as low priority until read one) Right parenthesis, then pop-up the first left parenthesis in the stack and all operators before it

Calculates the result from a suffix expression

Push a number into the stack when you see it. When you encounter an operator, it acts on two operands that pop up from the stack, and pushes the result out of the stack.

public class Postfix {
    //Used to record operators
    private static LinkedList<String> operators=new LinkedList<>();
    //Used to record output
    private static LinkedList<String> output=new LinkedList<>();
    //Used to show suffix expressions
    private static StringBuilder sb=new StringBuilder();

    public static void main(String[] args) {
        LinkedList<String> list=new LinkedList<>();
        Scanner scanner=new Scanner(System.in);
        String s;
        //End input with #sign, space between input characters for easy handling
        while (!(s=scanner.next()).equals("#")) {
            list.add(s);
        }
        transferToPostfix(list);
        scanner.close();
    }

    //Convert infix expression to suffix expression
    private static void transferToPostfix(LinkedList<String> list){
        Iterator<String> it=list.iterator();
        while (it.hasNext()) {
            String s = it.next();
            if (isOperator(s)) {
                if (operators.isEmpty()) {
                    operators.push(s);
                }
                else {
                    //If the read operator is not')'and the priority is higher or the same as that of the top element of the stack, push the operator onto the stack
                    if (priority(operators.peek())<=priority(s)&&!s.equals(")")) {
                        operators.push(s);
                    }
                    else if(!s.equals(")")&&priority(operators.peek())>priority(s)){
                        while (operators.size()!=0&&priority(operators.peek())>=priority(s)
                                &&!operators.peek().equals("(")) {
                            if (!operators.peek().equals("(")) {
                                String operator=operators.pop();
                                sb.append(operator).append(" ");
                                output.push(operator);
                            }
                        }
                        operators.push(s);
                    }
                    //If the operator read in is')', the first'('and all its preceding operators will pop up from the top of the stack
                    else if (s.equals(")")) {
                        while (!operators.peek().equals("(")) {
                            String operator=operators.pop();
                            sb.append(operator).append(" ");
                            output.push(operator);
                        }
                        //Eject'('
                        operators.pop();
                    }
                }
            }
            //Read-in non-operator
            else {
                sb.append(s).append(" ");
                output.push(s);
            }
        }
        if (!operators.isEmpty()) {
            Iterator<String> iterator=operators.iterator();
            while (iterator.hasNext()) {
                String operator=iterator.next();
                sb.append(operator).append(" ");
                output.push(operator);
                iterator.remove();
            }
        }
        System.out.println("Suffix: "+sb);
        calculate();
        //Collections.reverse(output);
    }

    //Calculates the result from a suffix expression
    private static void calculate(){
        LinkedList<String> mList=new LinkedList<>();
        String[] postStr=sb.toString().split(" ");
        for (String s:postStr) {
            if (isOperator(s)){
                if (!mList.isEmpty()){
                    int num1=Integer.valueOf(mList.pop());
                    int num2=Integer.valueOf(mList.pop());
                    if (s.equals("/")&&num1==0){
                        System.out.println("Divider cannot be zero");
                        return;
                    }
                    int newNum=cal(num2,num1,s);
                    mList.push(String.valueOf(newNum));
                }
            }
            else {
                //Numbers are pushed onto the stack
                mList.push(s);
            }
        }
        if (!mList.isEmpty()){
            System.out.println("result: "+mList.pop());
        }
    }

    //Determine whether an operator
    private static boolean isOperator(String oper){
        if (oper.equals("+")||oper.equals("-")||oper.equals("/")||oper.equals("*")
                ||oper.equals("(")||oper.equals(")")) {
            return true;
        }
        return false;
    }
    //Calculate Operator Priority
    private static int priority(String s){
        switch (s) {
            case "+":return 1;
            case "-":return 1;
            case "*":return 2;
            case "/":return 2;
            case "(":return 3;
            case ")":return 3;
            default :return 0;
        }
    }

    private static int cal(int num1,int num2,String operator){
        switch (operator){
            case "+":return num1+num2;
            case "-":return num1-num2;
            case "*":return num1*num2;
            case "/":return num1/num2;
            default :return 0;
        }
    }

}

Result

6 * ( 5 + ( 2 + 3 ) * 8 + 3 )
#
Suffix: 652 3 + 8 * + 3 + * 
result: 288

Added by alex_savin on Wed, 17 Jul 2019 20:21:08 +0300