calgorithmshunting-yard

Infix to postfix algorithm that takes care of unary operators


The I/p to the algo will be an expression like this:

a+(-b)
a*-b+c

i.e any expression that a standard C compiler would support.

Now I've the input already formatted as a stream of tokens , the tokens contain info whether its an operator or an operand. The algorithm should take this in and give me a postfix expression that I can evaluate.

If I use the standard conversion algo, I cant differentiate between an unary and a binary op. Like a*(-b) would give me ab-* ,which would evaluate in the wrong way.


Solution

  • If an operator is the first thing in your expression, or comes after another operator, or comes after a left parenthesis, then it's an unary operator.

    You have to use other symbols for unary operators in your output string, because otherwise it is not possible to distinguish between binary and unary variants in the postfix notation.