问题
I am trying to make a converter from postfix to infix notation and need some help. There is already a question about infix-to-postfix conversion, which gives an example I am failing to convert back. (Note: a minus sign is missing there!)
The following is the output of my converter, where the 1st "column" is postfix input, the 2nd is my infix output, and the 3rd is what I probably should get(?):
2 - = - 2 =? - 2 true
1 + 2 + = + 1 + 2 =? + 1 + 2 true
1 + 2 + + = + (+ 1 + 2) =? + 1 + + 2 false
1 + 2 + + 3 - - 4 - - = - (- (+ (+ 1 + 2) - 3) - 4) =? + 1 + + 2 - - 3 - - 4 false
Do you think that it is possible to solve this problem, or the last two lines are actually converted correctly? How would you write algorithm to solve this problem?
Please, assume that more operators (not only +
and -
) can be set as both unary and binary, where unary operators have higher precedence than binary ones.
References
- Ruby Quiz #148: Postfix to Infix, also via Google Groups
- Shunting-yard algorithm (C, Python, Perl) with unary operator support on LiteratePrograms
回答1:
Postfix notation does not have the concept of precedence, as the operands for any operator are always the top N values on the stack (which are then replaced by the result of the operator.
One problem with postfix notation is that it does not cope well with operator symbols that can refer to different operators depending on the number of operands (such as -, which can denote either unary or binary minus). The only way out of that is to ensure each operator has a unique symbol representing it.
来源:https://stackoverflow.com/questions/3438740/postfix-to-infix-with-unary-binary-operators