Converting infix notation to postfix notation

2 views
Skip to first unread message

Kon V

unread,
Sep 9, 2011, 1:04:36 AM9/9/11
to SJSUcmpe130
I was searching for the infix to postfix notation online, and came
upon a very easy algorithm I would like to share with the rest of the
class. The full text is available at http://www.ibm.com/developerworks/library/j-w3eval/index.html.
Another useful link is http://scriptasylum.com/tutorials/infix_postfix/infix_postfix.html,
it's an online infix to postfix converter that you can use to see if
your code is producing the right results.

Converting infix notation to postfix notation
To convert an expression in an infix expression to its equivalent in
postfix notation, we must know the precedence and associativity of
operators. Precedence or operator strength determines order of
evaluation; an operator with higher precedence is evaluated before one
of lower precedence. If the operators all have the same precedence,
then the order of evaluation depends on their associativity. The
associativity of an operator defines the order in which operators of
the same precedence are grouped (right-to-left or left-to-right).
Left associativity : A+B+C = (A+B)+C
Right associativity : A^B^C = A^(B^C)

The conversion process involves reading the operands, operators, and
parentheses of the infix expression using the following algorithm:
Initialize an empty stack and empty result string variable.

Read the infix expression from left to right, one character at a time.

If the character is an operand, append it to the result string.

If the character is an operator, pop operators until you reach an
opening parenthesis, an operator of lower precedence, or a right
associative symbol of equal precedence. Push the operator onto the
stack.

If the character is an opening parenthesis, push it onto the stack.

If the character is a closing parenthesis, pop all operators until you
reach an opening parenthesis and append them to the result string.

If the end of the input string is found, pop all operators and append
them to the result string.

Postfix expression evaluation

Evaluating a postfix expression is simpler than directly evaluating an
infix expression. In postfix notation, the need for parentheses is
eliminated and the priority of the operators is no longer relevant.
You can use the following algorithm to evaluate postfix expressions:
Initialize an empty stack.

Read the postfix expression from left to right.

If the character is an operand, push it onto the stack.

If the character is an operator, pop two operands, perform the
appropriate operation, and then push the result onto the stack. If you
could not pop two operators, the syntax of the postfix expression was
not correct.

At the end of the postfix expression, pop a result from the stack. If
the postfix expression was correctly formed, the stack should be empty.
Reply all
Reply to author
Forward
0 new messages