20. Shunting Yard Algorithm
Parse infix expressions into postfix using an operator stack
You type 3 + 4 * 2 into a calculator and expect 11, not 14. The calculator needs
to know that * binds tighter than + -- but the expression arrives as a flat sequence
of tokens, left to right. Somehow it has to respect precedence and associativity without
being told explicitly where to "start".
Edsger Dijkstra's shunting yard algorithm (1961) solves this elegantly. It reads an infix expression one token at a time and produces either postfix notation (Reverse Polish Notation) or an abstract syntax tree, using nothing more than a single output queue and a single operator stack. The name comes from the way operators get shunted onto and off the stack, like railroad cars in a switching yard.
Why Postfix?
Infix notation (3 + 4 * 2) is natural for humans but awkward for machines. Parentheses
and precedence rules create ambiguity that a simple left-to-right scan can't resolve.
Postfix notation (3 4 2 * +) eliminates all ambiguity. There are no parentheses, no
precedence rules to remember -- the order of the operands and operators tells you
everything:
| Notation | Expression | Evaluation order |
|---|---|---|
| Infix | 3 + 4 * 2 |
Need precedence rules |
| Postfix (RPN) | 3 4 2 * + |
Left to right, no rules needed |
| Prefix (Polish) | + 3 * 4 2 |
Right to left |
Once you have postfix, evaluation is trivial: scan left to right, push numbers onto a stack, and when you hit an operator, pop its operands, compute, and push the result.
Precedence and Associativity
The algorithm needs two pieces of information about each operator:
| Operator | Precedence | Associativity |
|---|---|---|
+ - |
1 | Left |
* / |
2 | Left |
^ |
3 | Right |
Precedence determines which operator binds tighter: * before +. Associativity
determines what happens when two operators have the same precedence: 2 - 3 - 4 is
(2 - 3) - 4 (left-associative), but 2 ^ 3 ^ 4 is 2 ^ (3 ^ 4) (right-associative).
The Algorithm
The shunting yard algorithm uses two data structures:
- An output queue (the result)
- An operator stack (temporary holding area)
-
Read a token
Read the next token from the input expression.
-
If it's a number, push to output
Numbers go directly to the output queue. They never touch the stack.
-
If it's an operator, manage the stack
While there is an operator on top of the stack, and either:
- the top operator has greater precedence, or
- they have equal precedence and the current operator is left-associative
...pop the top operator to the output queue. Then push the current operator onto the stack.
-
If it's a left parenthesis, push to stack
Left parentheses act as a barrier -- nothing gets popped past them.
-
If it's a right parenthesis, pop until matching left
Pop operators from the stack to the output queue until you reach the matching left parenthesis. Discard both parentheses (they don't appear in postfix).
-
When input is exhausted, flush the stack
Pop all remaining operators from the stack to the output queue. If a left parenthesis remains, the expression had mismatched parentheses.
The Core Invariant
The operator stack is always ordered by precedence from bottom to top (lowest at the bottom, highest at the top). Every time you push a new operator, you first pop everything that should execute before it. This is what enforces precedence without parentheses.
Worked Example: 3 + 4 * 2 - 1
Trace: infix to postfix
Token Action Stack Output
----- ------ ----- ------
3 number -> output [] [3]
+ push (stack empty) [+] [3]
4 number -> output [+] [3, 4]
* * > + -> just push [+, *] [3, 4]
2 number -> output [+, *] [3, 4, 2]
- - <= * -> pop * [+] [3, 4, 2, *]
- <= + -> pop + [] [3, 4, 2, *, +]
push - [-] [3, 4, 2, *, +]
1 number -> output [-] [3, 4, 2, *, +, 1]
EOF pop remaining [] [3, 4, 2, *, +, 1, -]
Result: 3 4 2 * + 1 -
Reading the postfix left to right: push 3, push 4, push 2, compute 4*2=8, compute 3+8=11, push 1, compute 11-1=10.
Let's trace why precedence worked: when * arrived, + was on the stack but has lower
precedence, so + stayed put. When - arrived, * has higher precedence, so * got
popped first (ensuring multiplication happens before subtraction). Then + has equal
precedence to - and is left-associative, so + gets popped too.
Worked Example with Parentheses: (1 + 2) * 3
Trace: parentheses override precedence
Token Action Stack Output
----- ------ ----- ------
( push to stack [(] []
1 number -> output [(] [1]
+ push (( is barrier) [(, +] [1]
2 number -> output [(, +] [1, 2]
) pop until ( [] [1, 2, +]
* push (stack empty) [*] [1, 2, +]
3 number -> output [*] [1, 2, +, 3]
EOF pop remaining [] [1, 2, +, 3, *]
Result: 1 2 + 3
Evaluation: push 1, push 2, compute 1+2=3, push 3, compute 33=9. The parentheses forced addition before multiplication.
Right Associativity: 2 ^ 3 ^ 4
The exponentiation operator ^ is right-associative, meaning 2 ^ 3 ^ 4 should
parse as 2 ^ (3 ^ 4), not (2 ^ 3) ^ 4.
Trace: right-associative operator
Token Action Stack Output
----- ------ ----- ------
2 number -> output [] [2]
^ push (stack empty) [^] [2]
3 number -> output [^] [2, 3]
^ ^ is right-assoc, so
equal prec does NOT pop [^, ^] [2, 3]
4 number -> output [^, ^] [2, 3, 4]
EOF pop remaining [] [2, 3, 4, ^, ^]
Result: 2 3 4 ^ ^
Evaluation: push 2, push 3, push 4, compute 3^4=81, compute 2^81.
The rightmost ^ executes first -- correct right-associative behavior.
The key difference: for left-associative operators, equal precedence triggers a pop. For right-associative operators, it doesn't. That single distinction is all it takes.
Evaluating Postfix with a Stack
Once you have postfix, evaluation is mechanical:
-
Read the next token
Scan the postfix expression left to right.
-
If it's a number, push it
Numbers go onto the evaluation stack.
-
If it's an operator, pop operands and compute
Pop the top two values (right operand first, then left), apply the operator, and push the result back.
-
The final value is the result
When the expression is exhausted, the stack holds exactly one value -- the answer.
Evaluating 3 4 2 * + 1 -
Token Action Stack
----- ------ -----
3 push [3]
4 push [3, 4]
2 push [3, 4, 2]
* pop 4,2 -> 8 [3, 8]
+ pop 3,8 -> 11 [11]
1 push [11, 1]
- pop 11,1 -> 10 [10]
Result: 10
This is exactly how HP calculators, Forth, and PostScript work. No parentheses, no precedence lookup -- just push and pop.
Pseudocode
function shuntingYard(tokens):
output = []
ops = []
for token in tokens:
if token is number:
output.push(token)
if token is operator o1:
while ops is not empty
and top of ops is not "("
and (prec(top) > prec(o1)
or (prec(top) == prec(o1) and o1 is left-assoc)):
output.push(ops.pop())
ops.push(o1)
if token is "(":
ops.push(token)
if token is ")":
while top of ops is not "(":
output.push(ops.pop())
ops.pop() // discard the "("
while ops is not empty:
output.push(ops.pop())
return output
Error Handling
The basic algorithm assumes well-formed input. In practice you need to handle:
| Error | Detection |
|---|---|
| Mismatched parentheses | ) encountered when no ( is on the stack, or ( remains on the stack after all input is consumed |
| Missing operand | During postfix evaluation, an operator tries to pop from an empty stack |
| Extra operands | After evaluation, more than one value remains on the stack |
| Unknown token | Token is neither a number, operator, nor parenthesis |
Extending to Functions
The shunting yard algorithm handles function calls with a small extension:
- When you see a function name (like
sin,max), push it onto the operator stack - When you see a
,(argument separator), pop operators to output until you reach a( - When you pop a
(and the token below it on the stack is a function, pop the function to output
This lets you parse expressions like max(2, 3) + sin(1) into postfix:
2 3 max 1 sin +.
Complexity
| Aspect | Value |
|---|---|
| Time | O(n) -- each token is pushed and popped at most once |
| Space | O(n) -- worst case all operators/parentheses on the stack |
The algorithm is remarkably efficient. It processes the entire expression in a single left-to-right pass with no backtracking.
Where It's Used
| Application | How shunting yard helps |
|---|---|
| Calculators | Parse and evaluate typed expressions with correct precedence |
| Compilers | Convert infix expressions to postfix or AST form during parsing |
| Spreadsheets | Evaluate cell formulas like =A1 * (B2 + C3) |
| Math renderers | Parse LaTeX-like expressions for layout and evaluation |
| Stack-based VMs | Generate postfix bytecode for virtual machines (Forth, JVM, PostScript) |
Shunting Yard vs. Recursive Descent
Recursive descent parsers (like Pratt parsers) solve the same problem by encoding precedence in the call stack via recursive function calls. Shunting yard uses an explicit stack instead. Both run in O(n) time. Shunting yard is simpler to implement for pure expression parsing; recursive descent is more flexible for full language grammars.
Key Takeaways
- The shunting yard algorithm converts infix expressions to postfix (RPN) in a single O(n) pass
- It uses two data structures: an output queue and an operator stack
- Precedence is enforced by popping higher-precedence operators before pushing lower ones
- Left vs. right associativity differs by a single comparison: equal precedence pops for left-associative, doesn't for right-associative
- Parentheses act as barriers on the stack -- nothing is popped past a left parenthesis
- Postfix expressions are trivially evaluated with a stack: push numbers, pop-and-compute on operators
- The algorithm extends naturally to handle functions, unary operators, and argument separators
Try It Yourself -- Shunting Yard Visualizer
Type an infix expression and step through the algorithm token by token. Watch how operators move between the stack and the output queue, and see the final postfix result evaluated.
Input
Operator Stack
Output Queue
Dijkstra's shunting yard algorithm is one of those rare algorithms that is both simple to implement and exactly correct. A single stack, a single queue, and a handful of comparison rules are enough to parse any expression a human can write -- with full support for precedence, associativity, and parentheses. It's the algorithm that lives inside every calculator, every spreadsheet formula bar, and countless compilers. If you've read the Pratt Parsing article in the Parsing series, you've seen the recursive alternative -- but for flat expression parsing, the shunting yard is hard to beat.