Algorithm to evaluate prefix expression?

前端 未结 2 428
夕颜
夕颜 2021-01-16 23:30

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

2条回答
  •  执笔经年
    2021-01-17 00:02

    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)
    

提交回复
热议问题