Algorithm to evaluate prefix expression?

牧云@^-^@ 提交于 2019-12-01 12:13:17

问题


I have a prefix expression that only has the 4 binary operators(+,-,*,/) .A straight forward way to evaluate such an expression is to convert it to a postfix expression and then evaluate that expression. But I am looking for an algorithm that does this directly without converting it to any other expression ?


回答1:


Simple recursion:

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)



回答2:


Use a stack. Place your vars and operators and start popping each stack, one for operators and the other for varaiablss (the number of pops depending on arity).



来源:https://stackoverflow.com/questions/14912045/algorithm-to-evaluate-prefix-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!