Infix expressions are converted to postfix expressions

       In the process of evaluating an expression (infix expression), if the expression is complex, it will waste a lot of computer memory and operation efficiency, while postfix expressions do not have such troubles. Theoretically, the postfix expression can calculate arbitrarily complex expressions, and the space consumed by it is only a small amount of stack space, and only the operators in the conversion process are stored in the stack. This article describes how to convert infix expressions to postfix expressions. The actual code is as follows:

import java.util.Stack;

public class MiddleToLast {
  public static String transfer(String str) {
    StringBuilder result = new StringBuilder("");
    Stack<Character> stack = new Stack<>();
    for (int i = 0; i < str.length(); i++) { // Loop to judge characters, the default input string here is a well-formed expression
      switch (str.charAt(i)) {
        case ' ':
          continue;
        case '+':
          result.append(plus(stack));
          break;
        case '-':
          result.append(sub(stack));
          break;
        case '*':
          result.append(mul(stack));
          break;
        case '/':
          result.append(div(stack));
          break;
        case '(':
          stack.push('(');
          break;
        case ')':
          result.append(parenthesis(stack));
          break;
        default:
          if (i > 0 && ('0' > str.charAt(i - 1) || str.charAt(i - 1) > '9')) {
            result.append(" ");
          }
          result.append(str.charAt(i));
      }
    }
    while (!stack.isEmpty()) {
      result.append(" " + stack.pop());
    }
    return result.toString();
  }

  // back parentheses
  private static String parenthesis(Stack<Character> stack) {
    StringBuilder result = new StringBuilder("");
    while (!stack.isEmpty()) {
      if (stack.peek() == '(') {
        stack.pop();
        break;
      }
      result.append(" " + stack.pop());
    }
    return result.toString();
  }

  // divide sign
  private static String div(Stack<Character> stack) {
    StringBuilder result = new StringBuilder("");
    while (!stack.isEmpty() && privilege(stack.peek(), '/')) {
      if (stack.peek() == '(') {
        break;
      }
      result.append(" " + stack.pop());
    }
    stack.push('/');
    return result.toString();
  }

  // Multiplication sign
  private static String mul(Stack<Character> stack) {
    StringBuilder result = new StringBuilder("");
    while (!stack.isEmpty() && privilege(stack.peek(), '*')) {
      if (stack.peek() == '(') {
        break;
      }
      result.append(" " + stack.pop());
    }
    stack.push('*');
    return result.toString();
  }

  // minus sign
  private static String sub(Stack<Character> stack) {
    StringBuilder result = new StringBuilder("");
    while (!stack.isEmpty() && privilege(stack.peek(), '-')) {
      if (stack.peek() == '(') {
        break;
      }
      result.append(" " + stack.pop());
    }
    stack.push('-');
    return result.toString();
  }

  // add
  private static String plus(Stack<Character> stack) {
    StringBuilder result = new StringBuilder("");
    while (!stack.isEmpty() && privilege(stack.peek(), '+')) {
      if (stack.peek() == '(') {
        break;
      }
      result.append(" " + stack.pop());
    }
    stack.push('+');
    return result.toString();
  }

  // Judge the operator priority, if ch1 is greater than ch2, return true
  private static boolean privilege(char ch1, char ch2) {
    if ((ch1 == '*' || ch1 == '/' || ch1 == '%') || ((ch1 == '+' || ch1 == '-') && (ch2 == '+' || ch2 == '-'))) {
      return true;
    }
    return false;
  }
}

        In the process of converting an infix expression to a postfix expression, there are three basic situations: ① operand ② operator ③ parentheses. Another issue to consider is operator precedence. The idea of ​​conversion is: when we encounter an operand, we will output the operand (number) directly, and when we encounter an operator, we will compare the operators saved at the top of the operator stack, such as the current operator takes precedence If the priority of the current operator is lower than the priority of the operation in the stack, the top operator in the stack will be popped and output, and continue to compare the top operator in the stack. And the priority order of the current operator, until there is no operator on the stack or the priority of the operator on the stack is lower than the current operator, or the operator on the stack is a straight bracket "(", and finally push the current operator onto the stack. For parentheses, if a straight parenthesis is encountered, the straight parentheses will be directly placed on the stack, and the next character will continue to be scanned. If a reverse parenthesis is encountered, the operators in the stack will be popped in turn until the straight parentheses are encountered.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326790755&siteId=291194637