CSC211 · 2081 · 5 marks
Convert the infix expression A+(((B-C)*(D-E)+F)/G$(H-I) into post expression using stack.
Convert the infix expression A+(((B-C)*(D-E)+F)/G$(H-I) into post expression using stack. [5]
Infix to Postfix Conversion Using Stack
Given
Infix expression: A+(((B-C)*(D-E)+F)/G$(H-I))
Note: The original problem text shows an apparent typo with unbalanced parentheses. Counting the brackets:
- Open parens:
(before((, giving 4 opening:( ( ( ( - Actually reading
A+(((B-C)*(D-E)+F)/G$(H-I))the balanced form has 4 opens and 4 closes.
I take the balanced expression: A+(((B-C)*(D-E)+F)/G$(H-I))
Operator precedence ($ = exponentiation, highest):
| Operator | Precedence |
|---|---|
$ | Highest |
*, / | Medium |
+, - | Lowest |
$ is right-associative; *, /, +, - are left-associative.
Solution
| Symbol | Action | Stack (bottom→top) | Postfix |
|---|---|---|---|
| A | output | A | |
| + | push | + | A |
| ( | push | + ( | A |
| ( | push | + ( ( | A |
| ( | push | + ( ( ( | A |
| B | output | + ( ( ( | A B |
| - | push | + ( ( ( - | A B |
| C | output | + ( ( ( - | A B C |
| ) | pop to ( | + ( ( | A B C - |
| * | push | + ( ( * | A B C - |
| ( | push | + ( ( * ( | A B C - |
| D | output | + ( ( * ( | A B C - D |
| - | push | + ( ( * ( - | A B C - D |
| E | output | + ( ( * ( - | A B C - D E |
| ) | pop to ( | + ( ( * | A B C - D E - |
| + | pop *, push + | + ( ( + | A B C - D E - * |
| F | output | + ( ( + | A B C - D E - * F |
| ) | pop to ( | + ( | A B C - D E - * F + |
| / | push | + ( / | A B C - D E - * F + |
| G | output | + ( / | A B C - D E - * F + G |
| $ | push | + ( / $ | A B C - D E - * F + G |
| ( | push | + ( / $ ( | A B C - D E - * F + G |
| H | output | + ( / $ ( | A B C - D E - * F + G H |
| - | push | + ( / $ ( - | A B C - D E - * F + G H |
| I | output | + ( / $ ( - | A B C - D E - * F + G H I |
| ) | pop to ( | + ( / $ | A B C - D E - * F + G H I - |
| ) | pop $, /, to ( | + | A B C - D E - * F + G H I - $ / |
| End | pop all | (empty) | A B C - D E - * F + G H I - $ / + |
Explanation of key steps:
- At the
+after(D-E): top of stack (inside brackets) is*, which has higher precedence than+, so*is popped, then+is pushed. - At final
): pop$then/until matching(. - At End: pop remaining
+.
Final Postfix Expression
$$\boxed{A\ B\ C-D\ E-*\ F+G\ H\ I-$\ /\ +}$$
That is: ABC-DE-*F+GHI-$/+
Verification: evaluating the postfix from left to right, A B C - builds (B-C), D E - builds (D-E), the * multiplies them, F + adds F, then G H I - $ builds G raised to (H-I), the / divides the bracketed sum by it, and the final + adds A, which reproduces the original infix expression exactly. The stack is empty at the end and every opening parenthesis was matched by a closing one, so the conversion is complete and correct.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.