Algorithm for evaluating postfix expressions:
Input: Postfix string
Output: Result of the expression
- Scan the Postfix string from left to right.
- Initialize an empty stack.
- A) If the scanned character is an operand, add it to the stack.
- B) If the scanned character is an operator, there will be at least two operands in the stack, otherwise report error. Pop 2 symbols from top of the stack (assuming operator is not unary) and apply the operator onto them. Push the result back.
- Repeat A) and B) until all characters are scanned.
- After all characters are scanned, we will have only one element in the stack. Return topStack.
Question #19: What will be the top of the stack after above algorithm has scanned till second ‘*’ in the postfix string: 123*4112+*+4–+ ?
Options:
- *
- 6
- 5
- 3
Solution:
Following will be the steps of the algorithm (comma indicates the position till the algorithm has scanned):
1, 23*4112+*+4–+
12, 3*4112+*+4–+
123, *4112+*+4–+
123*, 4112+*+4–+ => 16, 4112+*+4–+
164, 112+*+4–+
1641, 12+*+4–+
16411, 2+*+4–+
164112, +*+4–+
164112+, *+4–+ => 16413, *+4–+
16413*, +4–+ => 1643, +4–+
Hence, the correct answer is option 4.


