Chapter 7 · Simulation

Infix → Prefix Converter

← Chapter 7

Operator stack

Top
Ready.
Scanned
—
Intermediate output
—
Result
—
Convert the expression to build the steps.

Infix → Prefix Converter

In prefix (Polish) notation every operator comes before its operands, so A + B * C becomes + A * B C. Evaluating a prefix expression needs neither parentheses nor precedence rules.

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

  1. Reverse the expression and swap every ( with ).
  2. Scan the reversed expression with the postfix algorithm: operands go to the output, operators wait on the stack. On equal precedence pop only for ^ and push every other operator, because reversing the expression flips associativity.
  3. Reverse the intermediate output to get the prefix result.

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