Chapter 7 · Simulation

Infix → Postfix Converter

← Chapter 7

Operator stack

Top
Ready.
Scanned
—
Output so far
—
Result
—
Convert the expression to build the steps.

Infix → Postfix Converter

In postfix (reverse Polish) notation every operator follows its operands, so A + B * C becomes A B C * +. A postfix expression needs no parentheses and is evaluated left to right with a single stack.

How to use

  • Type an expression with single-letter or numeric operands, + - * / % ^ and parentheses (at most 22 tokens), then press Convert. Example loads a ready-made expression.
  • Next and Previous step through the conversion; Play runs it automatically, Cancel stops playback, and Reset returns to the start.

The algorithm (shunting-yard)

  • Operand: append it to the output.
  • (: push it. ): pop operators to the output until the matching (.
  • Operator: while the operator on top has higher precedence, or equal precedence and the incoming operator is left-associative, pop it to the output; then push the incoming operator. ^ is right-associative.
  • At the end of the input, pop whatever is left on the stack.

Precedence: ^ > * / % > + -. Running time: O(n).