formula: 3 + 4
parse tree:
+
/ \
3 4
RPN: 3 4 +
The RPN notation is <left_node> <right_node> <operator>. In this
case, the left and right nodes are both numbers, but the nodes may themselves
be other formulas. The parse tree is built out of the order of operations, so
the operation that takes place last is the root. Take this more complex
example:
formula: (3 + 4) * 2
parse tree:
* * is done last because of the () around 3 + 4
/ \
+ 2 The left node is 3 + 4 because that has to be
/ \ evaluated before (3 + 4) * 2 can be evaluated
3 4
RPN: 3 4 + 2 *
In this case, the "left node" is actually the formula "3 4 +", so that whole
formula is put into the left_node portion of the syntax. The "right node" is
2 and the "operator" is *.
Stacks can be used to evaluate a formula that is expressed in RPN notation. The pseudocode is:
until enter is hit
read next character from input stream
if it is a digit
put character back on the input stream
extract the number from the input stream
push the number onto the stack
else, if it is an operator (+ - * / %)
pop two values off the stack (two pop calls in a row)
if stack does not have two values
issue error (BNF is incorrect) and exit
compute the operation (a op b)
push the results of the operation onto the stack
else
issue an error about invalid input (not a number or valid operator)
once loop exits, the result is the top value on the stack
pop the result
if stack is not empty as a result of a pop
issue an error (stack should only contain the result at the end)
else
print the result
Use the following files to implement the BNF equation evaluator: