Reputation: 4944
I use the following logic to implement an infix to postfix conversion, to evaluate it later.
The loop on the infix conversion, and in each iteration, do the following:
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?
Upvotes: 1
Views: 574
Reputation: 133985
Looks like you need to change your rules so that you don't pop for successive unary operators. That is, given "--4":
-
as a unary operator, and push @
-
as a unary operator, see that the operator on the stack is also a unary operator, and push another @
.4
, and output it.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.
Upvotes: 2