简体   繁体   English

处理一元运算符的后缀算法的中缀

[英]Infix to postfix algorithm that takes care of unary operators

The I/p to the algo will be an expression like this:算法的 I/p 将是这样的表达式:

a+(-b)
a*-b+c

ie any expression that a standard C compiler would support.即标准 C 编译器支持的任何表达式。

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.就像 a*(-b) 会给我 ab-* ,这会以错误的方式进行评估。

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.您必须在输出字符串中为一元运算符使用另一个符号,否则无法区分后缀表示法中的二元和一元变体。

In your input, when you have 2 consecutive operators, the second operator will be unary.在您的输入中,当您有 2 个连续的运算符时,第二个运算符将是一元的。 If you have more consecutive operators, all but the first will be unary operators.如果您有更多的连续运算符,除第一个之外的所有运算符都是一元运算符。

Transform all your unary - operators to an operand -1 and an operator * , and remove all unary + operators.将所有一元-运算符转换为操作数-1和运算符* ,并删除所有一元+运算符。

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
)
)

You could simply convert -6 to 06- to eliminate unary operators completely.您可以简单地将-6转换为06-以完全消除一元运算符。 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. -仍然是二进制减号,而~成为否定符号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM