|
| 1 | +package com.thealgorithms.stacks; |
| 2 | + |
| 3 | +import java.util.Stack; |
| 4 | + |
| 5 | +/** |
| 6 | + * Evaluate a postfix (Reverse Polish) expression using a stack. |
| 7 | + * |
| 8 | + * <p>Example: Expression "5 6 + 2 *" results in 22. |
| 9 | + * <p>Applications: Used in calculators and expression evaluation in compilers. |
| 10 | + * |
| 11 | + * @author Hardvan |
| 12 | + */ |
| 13 | +public final class PostfixEvaluator { |
| 14 | + private PostfixEvaluator() { |
| 15 | + } |
| 16 | + |
| 17 | + /** |
| 18 | + * Evaluates the given postfix expression and returns the result. |
| 19 | + * |
| 20 | + * @param expression The postfix expression as a string with operands and operators separated by spaces. |
| 21 | + * @return The result of evaluating the postfix expression. |
| 22 | + * @throws IllegalArgumentException if the expression is invalid. |
| 23 | + */ |
| 24 | + public static int evaluatePostfix(String expression) { |
| 25 | + Stack<Integer> stack = new Stack<>(); |
| 26 | + |
| 27 | + for (String token : expression.split("\\s+")) { |
| 28 | + if (isOperator(token)) { |
| 29 | + int operand2 = stack.pop(); |
| 30 | + int operand1 = stack.pop(); |
| 31 | + stack.push(applyOperator(token, operand1, operand2)); |
| 32 | + } else { |
| 33 | + stack.push(Integer.parseInt(token)); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + if (stack.size() != 1) { |
| 38 | + throw new IllegalArgumentException("Invalid expression"); |
| 39 | + } |
| 40 | + |
| 41 | + return stack.pop(); |
| 42 | + } |
| 43 | + |
| 44 | + private static boolean isOperator(String token) { |
| 45 | + return token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/"); |
| 46 | + } |
| 47 | + |
| 48 | + private static int applyOperator(String operator, int a, int b) { |
| 49 | + return switch (operator) { |
| 50 | + case "+" -> a + b; |
| 51 | + case "-" -> a - b; |
| 52 | + case "*" -> a * b; |
| 53 | + case "/" -> a / b; |
| 54 | + default -> throw new IllegalArgumentException("Invalid operator"); |
| 55 | + }; |
| 56 | + } |
| 57 | +} |
0 commit comments