Stack Postfix Notation Algorithm

The Stack Postfix Notation Algorithm, also known as Reverse Polish Notation (RPN) algorithm, is a mathematical notation that presents arithmetic expressions in a format that is easier for computers to interpret and evaluate. Unlike the traditional infix notation, which places operators between operands (e.g., A + B), the postfix notation places operators after the operands (e.g., A B +). This unique arrangement eliminates the need for parentheses to indicate the order of operations and allows for a more efficient evaluation of expressions. To evaluate a postfix expression using the Stack Postfix Notation Algorithm, one must follow these steps: First, scan the expression from left to right, and for each character encountered, perform the following: If the character is an operand (i.e., a number), push it onto the stack. If the character is an operator (e.g., +, -, *, /), pop the top two values from the stack, apply the operator to them, and push the result back onto the stack. Once the entire expression has been processed, the final result will be the only value left on the stack. This algorithm enables a concise and efficient evaluation of complex expressions without the need for additional data structures or the complications arising from managing operator precedence and parentheses.
package Others;

import java.util.*;

public class StackPostfixNotation {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String post = scanner.nextLine();   // Takes input with spaces in between eg. "1 21 +"
        System.out.println(postfixEvaluate(post));
        scanner.close();
    }

    // Evaluates the given postfix expression string and returns the result.
    public static int postfixEvaluate(String exp) {
        Stack<Integer> s = new Stack<Integer>();
        Scanner tokens = new Scanner(exp);

        while (tokens.hasNext()) {
            if (tokens.hasNextInt()) {
                s.push(tokens.nextInt()); // If int then push to stack
            } else {    // else pop top two values and perform the operation
                int num2 = s.pop();
                int num1 = s.pop();
                String op = tokens.next();

                if (op.equals("+")) {
                    s.push(num1 + num2);
                } else if (op.equals("-")) {
                    s.push(num1 - num2);
                } else if (op.equals("*")) {
                    s.push(num1 * num2);
                } else {
                    s.push(num1 / num2);
                }

                //  "+", "-", "*", "/"
            }
        }
        tokens.close();
        return s.pop();
    }
}

LANGUAGE:

DARK MODE: