算法评估preFIX EX pression? [英] Algorithm to evaluate prefix expression?

查看:103
本文介绍了算法评估preFIX EX pression?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个preFIX EX pression,只有拥有4个二进制运算符(+, - ,*,/)。一个直来评估这样一个前pression前进的方向是将其转换为后缀EX pression,然后评估该EX pression。但我在寻找一种算法,直接做到这一点,而不将其转换为任何其他前pression?

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 ?

推荐答案

简单而又重复的:

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)

这篇关于算法评估preFIX EX pression?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆