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 ?
            Asked
            
        
        
            Active
            
        
            Viewed 4,297 times
        
    0
            
            
         
    
    
        Jens Erat
        
- 37,523
- 16
- 80
- 96
 
    
    
        Nikunj Banka
        
- 11,117
- 16
- 74
- 112
- 
                    Are you sure your expression is prefix? Can you paste a few examples? Infix expressions are hard to evaluate, and are usually converted to postfix. – Amir Afghani Feb 16 '13 at 17:54
2 Answers
5
            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)
 
    
    
        rici
        
- 234,347
- 28
- 237
- 341
0
            
            
        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).
 
    
    
        Srikant Krishna
        
- 881
- 6
- 11