data-structuresstackpostfix-notationinfix-notationshunting-yard

Infix to postfix problem with unary operators


I use the following logic to implement an infix to postfix conversion, to evaluate it later.

Notes: When I encounter a + or -, I can determine whether it's a binary or unary operator. If it's binary I add it to the stack as '+' or -, but if it's unary I add it as '@' or '$'.

The algorithm works well, except in a case where two unary operators are next to each other.

For example, "--4" becomes "@ 4 @", which is wrong.

What's wrong? What's the correct fix to this issue, that doesn't break other cases?


Solution

  • Looks like you need to change your rules so that you don't pop for successive unary operators. That is, given "--4":

    1. You identify the - as a unary operator, and push @
    2. You identify the next - as a unary operator, see that the operator on the stack is also a unary operator, and push another @.
    3. You see the 4, and output it.
    4. At the end of the string, you pop the two unary operators, giving you "4@@".

    And of course the unary operators should have higher precedence than any other operator, so that they'll always get popped before any other operator is pushed.