CSC211 Data Structures and Algorithms

Data Structures and AlgorithmsTU Board 2079

Evaluate the postfix expression 574 8/4+ using stack.

5

Answer

Rule for evaluating a postfix expression: scan from left to right. Push every operand. For an operator, pop two values (first pop = B, second pop = A), compute A op B, and push the result. At the end the stack holds the answer.

Expression: 5 7 4 - * 8 / 4 +

Symbol Action Stack (bottom → top)
5 push 5
7 push 5, 7
4 push 5, 7, 4
− B = 4, A = 7, 7 − 4 = 3, push 5, 3
* B = 3, A = 5, 5 × 3 = 15, push 15
8 push 15, 8
/ B = 8, A = 15, 15 / 8 = 1.875, push 1.875
4 push 1.875, 4
+ B = 4, A = 1.875, 1.875 + 4 = 5.875, push 5.875

Result = 5.875

(If the division is done in integer arithmetic, 15 / 8 = 1 and the result is 1 + 4 = 5. State which one you are using in the exam.)

Discussion

Loading…

More Data Structures and Algorithms questions

All Data Structures and Algorithms old questions