how to convert infix to postfix and prefix in java

how to convert infix to postfix and prefix in java

To convert an infix expression to a postfix or prefix expression in Java, you can use a stack data structure to process the operators and operands of the infix expression according to the rules of the desired notation.

Here is an example of how you can convert an infix expression to a postfix expression in Java:

refer‮ ‬to:lautturi.com
import java.util.Stack;

public class InfixToPostfix {
  private static int getPrecedence(char operator) {
    switch (operator) {
      case '+':
      case '-':
        return 1;
      case '*':
      case '/':
        return 2;
      case '^':
        return 3;
      default:
        return 0;
    }
  }

  public static String convert(String infix) {
    Stack<Character> stack = new Stack<>();
    StringBuilder postfix = new StringBuilder();
    for (int i = 0; i < infix.length(); i++) {
      char c = infix.charAt(i);
      if (Character.isLetterOrDigit(c)) {
        postfix.append(c);
      } else if (c == '(') {
        stack.push(c);
      } else if (c == ')') {
        while (!stack.isEmpty() && stack.peek() != '(') {
          postfix.append(stack.pop());
        }
        if (!stack.isEmpty() && stack.peek() == '(') {
          stack.pop();
        }
      } else {
        while (!stack.isEmpty() && getPrecedence(c) <= getPrecedence(stack.peek())) {
          postfix.append(stack.pop());
        }
        stack.push(c);
      }
    }
    while (!stack.isEmpty()) {
      postfix.append(stack.pop());
    }
    return postfix.toString();
  }
}

This code defines an InfixToPostfix class with a convert method that takes an infix expression as a string and returns its corresponding postfix expression as a string. The convert method uses a stack to process the operators and operands of the infix expression, according to the following rules:

  • If the current character is a letter or a digit, it is appended to the postfix expression.
  • If the current character is an opening parenthesis, it is pushed to the stack.
  • If the current character is a closing parenthesis, all operators on the stack are popped and appended to the postfix expression until an opening parenthesis is found. The opening parenthesis is then discarded.
  • If the current character is an operator, all operators on the stack with higher or equal precedence are popped and appended to the postfix expression, and then the current operator is pushed to the stack.

After all characters of the infix expression have been processed, any remaining operators on the stack are popped and appended to the postfix expression.

To convert an infix expression to a prefix expression, you can use a similar approach, but you will need to process the characters of the infix expression in reverse order, and append the operators and operands to the prefix expression instead of the postfix expression.

Created Time:2017-11-01 12:05:14  Author:lautturi