Reverse Polish notation – Wikipedia, the free encyclopedia
[edit] The RPN algorithm
Generalizing the above example, we can easily describe a method to evaluate any RPN expression:
* While there are input tokens left
o Read the next token from input.
o If the token is a number
Push it onto the stack.
o Otherwise, the token is a function. (Operators, like , are simply functions taking two arguments.)
It is known that the function takes n arguments.
So, pop the top n values from the stack.
# If there are fewer than n values on the stack
* (Error) The user has not input sufficient values in the expression.
Evaluate the function, with the values as arguments.
Push the returned results, if any, back onto the stack.
* If there is only one value in the stack
o The value is the result of the calculation.
* If there are more values in the stack
o (Error) The user input too many values.