Postfix to infix with unary/binary operators

梦想的初衷 提交于 2019-12-08 06:29:58

问题


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

  1. Ruby Quiz #148: Postfix to Infix, also via Google Groups
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!