import java.util.
Scanner;
import java.util.Stack;
public class InfixToPostfix {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter an infix expression:");
String infix = scanner.nextLine();
System.out.println("Postfix Expression: " + convertToPostfix(infix));
private static String convertToPostfix(String infix) {
StringBuilder postfix = new StringBuilder();
Stack<Character> stack = new Stack<>();
for (char c : infix.toCharArray()) {
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());
stack.pop();
} else {
while (!stack.isEmpty() && precedence(c) <= precedence(stack.peek())) {
postfix.append(stack.pop());
stack.push(c);
}
}
while (!stack.isEmpty()) {
postfix.append(stack.pop());
return postfix.toString();
private static int precedence(char op) {
return switch (op) {
case '+', '-' -> 1;
case '*', '/' -> 2;
case '^' -> 3;
default -> -1;
};