Let’s recall how we write a mathematical equation with basic arithmetical operations. Here is an example of a simple equation.
(((2 + 2) * 3) - 10)
This is the form that we use to write equations in normal. This notation is called infix notation. Due to the involvement of brackets, computers do not use this notation. Instead, they use either post-fix or prefix notation.
In post-fix notation, the operands come before their operators. Below is the previous equation in post-fix notation:
2 2 + 3 * 10 -
For the evaluation of post-fix notation, we use the stack data structure. The following are the rules of evaluating post-fix notation using stack:
Let’s evaluate the given example.
As the expression is empty, we simply pop an element from the stack, and that is the result of the expression.
Note: While applying the operator in the postfix evaluation, we place the second popped character at the first position, then the operator, and then the first popped element.
In prefix notation, the operators come before their operands. It is also called Polish notation, or Warsaw notation. Below is the same equation in prefix notation:
- * + 2 2 3 10
For the evaluation of prefix notation, we also use the stack data structure.
The following are the rules for evaluating prefix notation using a queue:
Let’s evaluate the given example.
As the expression is empty, we simply pop an element from the stack, and that is the result of the expression.
Note: In the prefix evaluation, while applying the operator, we placed the first popped character at the first position, then the operator, and then the second popped element.
Free Resources