以下具有单个数字操作数的后缀表达式是使用堆栈求值的:
8 2 3 ^ / 2 3 * + 5 1 * -
请注意,^是幂运算符。评估第一个*之后的堆栈的前两个元素是:
(A) 6、1
(B) 5、7
(C) 3、2
(D) 1、5答案: (A)
说明:用于评估任何后缀表达式的算法非常简单:
1. While there are input tokens left
o Read the next token from input.
o If the token is a value
+ Push it onto the stack.
o Otherwise, the token is an operator
(operator here includes both operators, and functions).
* It is known a priori that the operator takes n arguments.
* If there are fewer than n values on the stack
(Error) The user has not input sufficient values in the expression.
* Else, Pop the top n values from the stack.
* Evaluate the operator, with the values as arguments.
* Push the returned results, if any, back onto the stack.
2. If there is only one value in the stack
o That value is the result of the calculation.
3. If there are more values in the stack
o (Error) The user input has too many values.
算法来源:http://en.wikipedia.org/wiki/Reverse_Polish_notation#The_postfix_algorithm
让我们针对给定的表达式运行上述算法。
前三个标记是值,因此只需将其推入即可。推入8、2和3之后,堆栈如下
8, 2, 3
读取^时,将弹出前两个,并计算power(2 ^ 3)
8, 8
读取/时,弹出前两个并执行除法(8/8)
1
接下来的两个标记是值,因此只需将其推入即可。推入2和3之后,堆栈如下
1, 2, 3
*出现时,前两个弹出并执行乘法。
1, 6
这个问题的测验