Using Stacks to Convert Between Infix and Postfix Expressions

Arithmetic Expression Evaluation

This section illustrates two common stack-based algorithms for arithmetic expression manipulation:

evaluating an arithmetic expression written in postfix form.

converting an infix expression to postfix form.

Converting an infix expression (the usual form) to postfix means to write the expression so that the operators come after the operands. There are no parentheses in such expressions. For simplicity we'll look at only the standard binary operators:

+, –, *, /

Postfix expression evaluation

In the postfix expression evaluation algorithm, the stack contains only numbers. Here is a sketch of the algorithm:

for each expression token:
if the token is a number:
push it
else (the token is an operator, OP):
second = pop();
first = pop();
compute: result = first OP second
push the result on the stack
when there are no more tokens, pop the answer off the stack

Infix to Postfix conversion

The infix-to-postfix conversion algorithm is more complicated. It is extremely simple if all operators have the same precedence (such as "+" and "–") and there are no parentheses. Adding parentheses and operators of differing precedence introduces complications.

The goal of the algorithm is to construct an output string which is the equivalent postfix form of a given infix expression. The stack will hold operators and left parentheses. One key observation is that the numbers stay in the same order as in the infix expression.

Here is a sketch of the algorithm:

for each expression token:
if the token is a number:
add it to output
else if the token is a left paren:
push it
else if the token is a right paren:
pop and add to output all tokens on stack up to left paren
pop the left paren, but don't add to output
else if the token is an operator:
if stack is empty or the top is a left paren:
push it
else if the stack top is a lower precedence operator:
push it
else
pop and add to output all operators of higher or equal precedence
push it
when there are no more tokens,
pop and add to output all remaining operators on stack

Observe in the way numbers are handled that the numbers appear in the same order as in the infix expression. Here are some examples:

Java Programs

These two programs are intended to be in the demo package.

The Infix2Postfix program enters and processes an arithmetic expression (in standard infix form), generating an output of the arithmetic expression in postfix form. Operands are assumed to be unsigned non-negative integers.

demo.Infix2Postfix

The PostfixEvaluation program evaluates a postfix expression. Again, operands are assumed to be unsigned non-negative integers.