以下带有单个数字操作数的后缀表达式是使用堆栈计算的:
8 2 3 ^ / 2 3 * + 5 1 * -
请注意,^ 是幂运算符。评估第一个 * 后堆栈的顶部两个元素是:
(一) 6, 1
(二) 5、7
(C) 3、2
(四) 1, 5答案:(一)
说明:评估任何后缀表达式的算法相当简单:
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
这个问题的测验