Computer Science
For the following arithmetic expression:
((2 + 3) * (4 / 2)) + 2
Show step-by-step process for matching parentheses using stack data structure.
Python Stack
6 Likes
Answer
For matching parentheses, we can push in the stack for each opening parenthesis of the expression and pop from the stack for each closing parenthesis.
Scanning from left to right:
| Symbol | Stack | Action |
|---|---|---|
| ( | ( ↑ — top | Push |
| ↑ | ||
| ( | (( | Push |
| ↑ | ||
| 2 | .......... | |
| + | .......... | |
| 3 | .......... | |
| ) | ( | Pop |
| ↑ | ||
| * | .......... | |
| ( | (( | Push |
| ↑ | ||
| 4 | .......... | |
| / | .......... | |
| 2 | .......... | |
| ) | ( | Pop |
| ↑ | ||
| ) | #Empty | Pop |
| + | .......... | |
| 2 | #Empty | .......... |
Empty stack => Balanced Parentheses
Answered By
2 Likes
Related Questions
Find the output of the following code:
answer = []; output = '' answer.append('T') answer.append('A') answer.append('M') ch = answer.pop() output = output + ch ch = answer.pop() output = output + ch ch = answer.pop() output = output + ch print("Result=", output)Write a program to reverse a string using stack.
Evaluate following postfix expression while showing status of stack after each operation given A = 3, B = 5, C = 1, D = 4.
AB + C *
Evaluate following postfix expression while showing status of stack after each operation given A = 3, B = 5, C = 1, D = 4.
AB * C / D *