关于后缀转换的说明

时间:2019-11-16 08:28:18

标签: stack postfix-notation infix-notation

因此,此表达式A-B + C *(D / E)结果为A B-C D E / * +

我认为在将中缀转换为后缀时,必须将运算符保留在堆栈中,直到看到其后或表达式末尾具有较低优先级的运算符,然后将其全部写下来。

但是减号的优先级与加号的优先级相同,那么为什么要写下减号而不将其保留在堆栈中?

我认为我对转换方法的理解有些奇怪。请提供解释,最好提供逐步解决方案。我真的对减号发生了什么感到困惑,因为我对转换的理解不同。非常感谢。

1 个答案:

答案 0 :(得分:1)

Shunting yard algorithm规则规定:

if the token is an operator, then:
    while ((there is a function at the top of the operator stack)
           or (there is an operator at the top of the operator stack with greater precedence)
           or (the operator at the top of the operator stack has equal precedence and is left associative))
          and (the operator at the top of the operator stack is not a left parenthesis):
        pop operators from the operator stack onto the output queue.

请注意第二个or条件:位于运算符堆栈顶部的运算符具有相同的优先级,并且保持关联性

+-运算符具有相同的优先级,并且是左关联的。因此,当您看到-时,将删除+运算符。

另请参见https://www.geeksforgeeks.org/operator-precedence-and-associativity-in-c/。尽管这特定于C,但是大多数语言对通用运算符使用相同的优先级和关联性。