Data Structures and AlgorithmsTU Board 2079
Evaluate the postfix expression 574 8/4+ using stack.
5Answer
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
Define circular queue. How queue differ from stack. Write a program to implement linear queue.TU Board 208110What is AVL tree? How heap differ from tree? Construct an AVL tree for data 24,12,8,15,35,30,57,40,45 and 78.TU Board 208110Define list. How can you use linked list to implement stack? Explain circular linked list.TU Board 208110Explain big oh notation in brief. Find big oh of the following function: f(x) = 5x^4 + 9x^2 + 7x + 9.TU Board 20815Convert the infix expression A+(((B C) (D E)+F)/G)$(H I) into post expression using stack.TU Board 20815Write a program to find GCD of two numbers using recursion.TU Board 20815