From 4e8d5534052379b39681b0891f70a9e2e75fdd68 Mon Sep 17 00:00:00 2001 From: Laiba Ashfaq Date: Sun, 12 Oct 2025 14:49:18 +0500 Subject: [PATCH] Add Infix to Postfix conversion implementation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Infix Expression: Operator is between operands → A + B Postfix Expression: Operator is after operands → A B + We use a stack to temporarily hold operators and handle operator precedence. --- .../stacks/InfixToPostfixevaluator.java | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 src/main/java/com/thealgorithms/stacks/InfixToPostfixevaluator.java diff --git a/src/main/java/com/thealgorithms/stacks/InfixToPostfixevaluator.java b/src/main/java/com/thealgorithms/stacks/InfixToPostfixevaluator.java new file mode 100644 index 000000000000..6b2ecad0f0db --- /dev/null +++ b/src/main/java/com/thealgorithms/stacks/InfixToPostfixevaluator.java @@ -0,0 +1,69 @@ +import java.util.Stack; + +public class InfixToPostfix { + + // Function to check operator precedence + static int precedence(char ch) { + switch (ch) { + case '+': + case '-': + return 1; + case '*': + case '/': + return 2; + case '^': + return 3; + } + return -1; + } + + // Function to convert infix to postfix + static String convert(String expression) { + String result = ""; + Stack stack = new Stack<>(); + + for (int i = 0; i < expression.length(); i++) { + char c = expression.charAt(i); + + // If character is an operand, add it to output + if (Character.isLetterOrDigit(c)) { + result += c; + } + + // If character is '(', push it to stack + else if (c == '(') { + stack.push(c); + } + + // If character is ')', pop until '(' is found + else if (c == ')') { + while (!stack.isEmpty() && stack.peek() != '(') { + result += stack.pop(); + } + stack.pop(); // remove '(' + } + + // If character is operator + else { + while (!stack.isEmpty() && precedence(c) <= precedence(stack.peek())) { + result += stack.pop(); + } + stack.push(c); + } + } + + // Pop all remaining operators from stack + while (!stack.isEmpty()) { + result += stack.pop(); + } + + return result; + } + + // Main method to test the program + public static void main(String[] args) { + String infix = "A*(B+C)/D"; + System.out.println("Infix: " + infix); + System.out.println("Postfix: " + convert(infix)); + } +}