Member-only story
Reverse Polish Notation
Reverse Polish notation (RPN) or simply postfix notation, is a mathematical notation in which operators follow their operands.
In RPN, mathematical expressions are written in a postfix form, where operators are placed after their operands. For example, the infix expression 3 + 4 would be written as 3 4 + in RPN.
To evaluate an expression in RPN, a stack-based algorithm is commonly used. Here’s how it works:
- Start with an empty stack.
- Scan the expression from left to right.
- If the current token is an operand, push it onto the stack.
- If the current token is an operator, pop the top two operands from the stack, apply the operator to them, and push the result back onto the stack.
- Continue this process until all tokens have been processed.
- The final result is the value remaining on the stack.
Example
Let’s evaluate the RPN expression 3 4 + 5 *.
- Start with an empty stack.
- Scan the expression from left to right.
- Push
3onto the stack (operand). - Push
4onto the stack (operand). - Encounter
+(operator). Pop4and3, add them (3 + 4 = 7), and push7onto the stack. - Push
5onto the stack (operand). - Encounter
*(operator). Pop5and7, multiply them (7 * 5 = 35), and push…