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.comimport 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:
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.