UNIHIVE

Study Hub UNIPORT CSC 392

CSC 392 · Automata Theory, Computability and Formal Languages

Translating infix and postfix expressions

Infix, prefix and postfix notation, converting with the shunting-yard algorithm, and evaluating postfix with a stack.

Our notes

2 min read

Three notations

NotationExampleOperator position
Infix(3 + 4) × 5between operands
Prefix (Polish)× + 3 4 5before
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:

  1. Operand: write it to the output.
  2. 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.
  3. ( : push it.
  4. ) : pop to the output until ( and discard both brackets.
  5. At the end, pop everything to the output.

Worked example

Infix: A + B × C − D (× before + and −; all left-associative).

TokenOutputStack
AA
+A+
BA B+
×A B+ ×
CA B C+ ×
−A B C × +−
DA B C × + D−
endA 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.

All CSC 392 topics

Report

Sign in to report this. It is free.

Is this your work (a lecturer, author or publisher)? Ask us to take it down.