Advertisements
Advertisements
प्रश्न
For the following arithmetic expression:
((2+3)*(4/2))+2
Show step-by-step process for matching parentheses using stack data structure.
थोडक्यात उत्तर
Advertisements
उत्तर
Rules for matching parentheses.
- PUSH in the stack, if encounter opening parenthesis ‘(‘.
- POP from the stack, if encounter closing parenthesis ‘)’
- At the end; if stack is empty – Then Parentheses are balanced, otherwise Parentheses are unbalanced.
Given Expression : ( ( 2 + 3 ) * ( 4 / 2 ) ) + 2
Scanning from left to right –
| Symbol | Stack, Initially Stack is Empty [ ] | Action |
| [ ] | ||
| ( | ( | PUSH ‘(‘ |
| ( | ( ( | PUSH ‘(‘ |
| 2 | ( ( | Ignore |
| + | ( ( | Ignore |
| 3 | ( ( | Ignore |
| ) | ( | POP |
| * | ( | Ignore |
| ( | ( ( | PUSH |
| 4 | ( ( | Ignore |
| / | ( ( | Ignore |
| 2 | ( ( | Ignore |
| ) | ( | POP |
| ) | [ ] | POP |
| + | [ ] | Ignore |
| 2 | [ ] | Ignore |
| End of Symbol |
shaalaa.com
Notations for Arithmetic Expressions
या प्रश्नात किंवा उत्तरात काही त्रुटी आहे का?
