0

我查看了调车场的 wiki 页面,因为在我的调车场处理链式一元减号运算符时遇到问题,但 wiki 算法似乎无法处理它。

Wiki算法供参考:

/* This implementation does not implement composite functions,functions with variable number of arguments, and unary operators. */

while there are tokens to be read:
    read a token.
    if the token is a number, then:
        push it to the output queue.
    if the token is a function then:
        push it onto the operator stack 
    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 bracket):
            pop operators from the operator stack onto the output queue.
        push it onto the operator stack.
    if the token is a left bracket (i.e. "("), then:
        push it onto the operator stack.
    if the token is a right bracket (i.e. ")"), then:
        while the operator at the top of the operator stack is not a left bracket:
            pop the operator from the operator stack onto the output queue.
        pop the left bracket from the stack.
        /* if the stack runs out without finding a left bracket, then there are mismatched parentheses. */
if there are no more tokens to read:
    while there are still operator tokens on the stack:
        /* if the operator token on the top of the stack is a bracket, then there are mismatched parentheses. */
        pop the operator from the operator stack onto the output queue.
exit.

假设我有以下表达式---1,我希望 rpn 输出为1---,但实际发生的情况如下:


迭代1: operator stack: [] output queue: []

要读取的令牌是 a-所以我们推入操作员堆栈


迭代2: operator stack: [-] output queue: []

要读取的令牌是-. 有一个-操作员堆栈,我们应该将其弹出到输出队列中。然后我们将令牌推送到操作员堆栈上。


迭代 3: operator stack: [-] output queue: [-]

错误- 我们不应该-在输出队列中有一个。(因为没有意义,所以不会继续算法)

4

0 回答 0