CSC 392 · Automata Theory, Computability and Formal Languages
Our notes
2 min readThree notations
| Notation | Example | Operator position |
|---|---|---|
| Infix | (3 + 4) × 5 | between operands |
| Prefix (Polish) | × + 3 4 5 | before |
| Postfix (reverse Polish) | 3 4 + 5 × | after |
Postfix needs no brackets and no precedence rules: the order of the symbols says everything. Compilers often turn expressions into postfix (or a tree) before generating code, and stack machines (the Java virtual machine) work this way.
Converting infix to postfix: the shunting-yard algorithm (Dijkstra)
Read the infix tokens left to right with an operator stack:
- Operand: write it to the output.
- Operator o: while the top of the stack is an operator of higher precedence, or equal precedence and o is left-associative, pop it to the output; then push o.
- ( : push it.
- ) : pop to the output until ( and discard both brackets.
- At the end, pop everything to the output.
Worked example
Infix: A + B × C − D (× before + and −; all left-associative).
| Token | Output | Stack |
|---|---|---|
| A | A | |
| + | A | + |
| B | A B | + |
| × | A B | + × |
| C | A B C | + × |
| − | A B C × + | − |
| D | A B C × + D | − |
| end | A B C × + D − |
Postfix: A B C × + D −.
Worked example with brackets
(A + B) × (C − D) becomes A B + C D − ×.
Evaluating postfix with a stack
Read left to right: push operands; for an operator, pop two values (the second popped is the left operand), apply, push the result.
Evaluate 6 2 3 × + 4 −:
- push 6, 2, 3; × → 2 × 3 = 6, stack 6 6; + → 12; push 4; − → 12 − 4 = 8.
Check with infix 6 + 2 × 3 − 4 = 8 ✓.
Expression trees
An expression is also a binary tree with operators at the nodes: a post-order traversal gives postfix, pre-order gives prefix, in-order (with brackets) gives infix.
Exams usually ask
- Convert infix to postfix and prefix, with and without brackets.
- Evaluate a postfix expression with a stack, showing the stack.
- Explain why postfix needs no brackets.
Common mistake
Popping operands in the wrong order. For a − b the stack holds a then b; the first pop gives b (the right operand), the second a.
Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.
No reading links here yet
Our team adds free books, videos and practice for each topic, and opens every link before it goes up.