How do you evaluate the expression in postfix form?
For example, what is the answer of 5 10 2 * + 3 -
-
When you see a number, you push it into a
stack.
-
When you see an operator, you pop two numbers from the stack, first pop store into right
and second pop store in left and do operation
like "left op right", eg. 10 - 8, 4 * 7,... etc.
You store the answer back to stack.
So, in our example, 5 10 2 * + 3 -
,
- we push 5, 10, and 2 into stack, like
.
-
Then you see an operator and pop 2 numbers out from the stack.
-
You will do 10*2 = 20.
- Push 20 into stack.
-
After that you see +, you pop two numbers out. This
point of time the stack is empty.
- You do 5 + 20=25.
- You push the answer 25 into the
stack. You read 3 and push into stack.
-
Finally, you see a subtraction sign and pop two numbers out.
- Do 25 -
3 =22.
- Since there is no more element in the expression, you got the solution 22
for this expression..