What is Postfix Notation?
In postfix notation, also known as Reverse Polish Notation, you write the operator right after its two operands instead of between them.
So the everyday expression 3 + 4 becomes 3 4 + once converted. There's no ambiguity about order of operations here: the position of each operator in the string already tells you exactly when to apply it, so parentheses become unnecessary.
Note: Higher precedence means the operation will happen first. When operators have equal precedence, they are evaluated left-to-right (except for exponentiation which is right-to-left).
Infix to Postfix Conversion Steps
- Initialize an empty stack and an empty output string.
- Scan the infix expression from left to right.
- If the element is an operand, add it to the output.
- If the element is a '(', push it onto the stack.
- If the element is a ')', pop from the stack and add to output until '(' is encountered.
- If the element is an operator, pop from the stack all operators with higher or equal precedence, then push the current operator.
- After scanning, pop all remaining operators from the stack.
How Does It Work?
Take (A + B) * (C - D). The amber token is the one being scanned, the stack holds operators waiting for their operands, and the output grows left to right:
1. Scan '(' — '(' is pushed onto the stack
2. Scan 'A' — 'A' is an operand, so it goes straight to the output
3. Scan '+' — Push '+' onto the stack
4. Scan 'B' — 'B' is an operand, so it goes straight to the output
5. Scan ')' — Pop operators to the output until '(' is found
6. Scan '*' — Push '*' onto the stack
7. Scan '(' — '(' is pushed onto the stack
8. Scan 'C' — 'C' is an operand, so it goes straight to the output
9. Scan '-' — Push '-' onto the stack
10. Scan 'D' — 'D' is an operand, so it goes straight to the output
11. Scan ')' — Pop operators to the output until '(' is found
12. End of scan — Scan finished — pop everything left on the stack
Final postfix: A B + C D - *. Notice the operands never touch the stack — only operators wait there, and each one is released the moment an operator of equal or higher precedence arrives, or its bracket closes.
Operator Precedence Table
| Operator | Meaning | Precedence |
|---|---|---|
| ( ) | Parentheses | Highest |
| ^ % | Exponentiation / Modulus | 2 |
| * / | Multiplication / Division | 3 |
| + - | Addition / Subtraction | 4 (Lowest) |
Note: Higher precedence means the operation will happen first. When operators have equal precedence, they are evaluated left-to-right (except for exponentiation which is right-to-left).