评估前缀表达式的算法?

时间:2013-02-16 15:44:42

标签: algorithm language-agnostic prefix infix-notation postfix-notation

我有一个只有4个二元运算符(+, - ,*,/)的前缀表达式。评估这样一个表达式的直接方法是将它转换为后缀表达式,然后计算该表达式。但我正在寻找一种直接执行此算法而不将其转换为任何其他表达式的算法?

2 个答案:

答案 0 :(得分:4)

简单递归:

Evaluate(input):
  Read a token from input.
  If the token is a value:
    Return the value of the token
  If the token is a binary operator:
    Let first_argument = Evaluate(input)
    Let second_argument = Evaluate(input)
    Return apply(operator, first_argument, second_argument)

答案 1 :(得分:0)

使用堆栈。放置你的变量和运算符,然后开始弹出每个堆栈,一个用于操作符,另一个用于varaiablss(弹出的数量取决于arity)。

相关问题