Infix to postfix algorithm that takes care of unary operators

不羁的心 提交于 2019-12-09 18:18:41

问题


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.


回答1:


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 another 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.




回答2:


In your input, when you have 2 consecutive operators, the second operator will be unary. If you have more consecutive operators, all but the first will be unary operators.

Transform all your unary - in an operand -1 and an operator *, and remove all unary +

If the first element is an operator, it is an unary operator.

Parenthesis are a special case, but you can do a first pass in which you ignore them. In the following example - is consecutive to *.

4*(-(5))

and your tokens would become:

4
*
(
-1
*
(
5
)
)



回答3:


You could simply convert -6 to 06- to eliminate unary operators completely. I like this approach since it is more orthogonal and you do not need to take care of special cases when processing.

An alternative approach is to use different symbols for the unary and the binary versions of operators using the same symbol, eg. - remains binary minus and ~ becomes negation sign.



来源:https://stackoverflow.com/questions/17254080/infix-to-postfix-algorithm-that-takes-care-of-unary-operators

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