From bdd0b6131d41f21d9eba1144df6167b266237055 Mon Sep 17 00:00:00 2001 From: Prasoon Pandey <138553057+Prasoon31Pandey@users.noreply.github.com> Date: Sun, 5 Oct 2025 19:24:22 +0530 Subject: [PATCH] Add Infix to Postfix Converter using Stack (Java) This program converts an infix expression (like A+B*C) into a postfix expression (A B C * +) using the Stack data structure. It follows operator precedence and associativity rules to ensure the correct order of operations. Example: Input: A+B*C Output: ABC*+ Time Complexity: O(n) Space Complexity: O(n) --- InfixToPostfix.java | 72 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 InfixToPostfix.java diff --git a/InfixToPostfix.java b/InfixToPostfix.java new file mode 100644 index 00000000..ab1f8535 --- /dev/null +++ b/InfixToPostfix.java @@ -0,0 +1,72 @@ +import java.util.Stack; + +/** + * This class converts an infix expression (e.g. A+B*C) + * into a postfix expression (e.g. A B C * +) + * using the Stack data structure. + * + * Time Complexity: O(n) + * Space Complexity: O(n) + */ +public class InfixToPostfix { + + private static boolean isOperand(char c) { + return Character.isLetterOrDigit(c); + } + + private static int precedence(char op) { + switch (op) { + case '^': return 3; + case '*': case '/': return 2; + case '+': case '-': return 1; + default: return -1; + } + } + + public static String convert(String exp) { + StringBuilder result = new StringBuilder(); + Stack stack = new Stack<>(); + + for (int i = 0; i < exp.length(); i++) { + char c = exp.charAt(i); + + // Operand → add to result + if (isOperand(c)) { + result.append(c); + } + // Opening parenthesis + else if (c == '(') { + stack.push(c); + } + // Closing parenthesis + else if (c == ')') { + while (!stack.isEmpty() && stack.peek() != '(') { + result.append(stack.pop()); + } + if (!stack.isEmpty() && stack.peek() == '(') { + stack.pop(); + } + } + // Operator + else { + while (!stack.isEmpty() && precedence(stack.peek()) >= precedence(c)) { + result.append(stack.pop()); + } + stack.push(c); + } + } + + // Pop remaining operators + while (!stack.isEmpty()) { + result.append(stack.pop()); + } + + return result.toString(); + } + + public static void main(String[] args) { + String exp = "A+B*C"; + System.out.println("Infix: " + exp); + System.out.println("Postfix: " + convert(exp)); + } +}