让我们看看我是否可以为你分解它。调车码算法通过破坏中缀符号来执行以下操作之一:
- 要么产生一个后缀符号字符串(也称为逆波兰符号)
- 或抽象语法树。
在你的情况下,它是后缀表示法。
[注意:我希望你知道后缀符号,如果没有,请阅读this。]
现在,后缀表示法使计算数学表达式变得非常容易。我将向您展示如何评估后缀符号:
In a simple description:
(1) Infix: A + B
Postfix: A B +
(2) Infix: A + B * C
Postfix: A B C * +
Let's observe the part A+B*C i.e. A+(B*C)
If we represent it in Postfix, it would be like: A B C * +(by applying shunting-yard)
Now, the algorithm to calculate it
(1) Take a stack
(2) When we see a number, we push it to stack
(3) When we see a operator, we pop two numbers out of stack and calculate them with help of operator and push the result into stack again
(4) We do it till the end
(5) At last, only a number would be left in stack, that is our answer.
Let's visualise it:
(1) [A]
(2) [A, B]
(3) [A, B, C]
(4) [A, R1] where R1 = B*C
(5) [R2] where R2 = A+R1
我希望,你已经明白,调车场将帮助你将中缀转换为后缀,然后,你可以轻松地评估后缀表示法。
现在,问题是如何检测a++b 错误:
现在,观察 a、+、+、b 标记会发生什么(正如您在评论中所说:a++b 被标记化为 a、+、+、b 标记):
我从*中获取了伪代码(懒惰,不想自己写):
else if the token is an operator then:
while ((there is a operator at the top of the operator stack)
and ((the operator at the top of the operator stack has greater precedence)
or (the operator at the top of the operator stack has equal precedence and the token 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.
push it onto the operator stack.
据此:a、+、+、b 在输出队列中将采用以下形式:
a, b, +, +
a, b, +, + 完全是错误的,因为根据后缀评估规则会发生以下情况:
1. [a] // output queue is now [b, +, +]
2. [a, b] // output queue is now [+, +]
3. [r1] // output queue is now [+]
4. error // cause: notice there's still one '+' operator left in queue
// but, only one number 'r1' left in the 'stack'
// so, error
我希望你现在清楚了......