You are on page 1of 4

CSC248 FUNDAMENTAL OF DATA STRUCTURES

EXERCISE : STACK 2

Question 1

a) Convert the following expression into postfix notation using stack diagram.
i. A+B–C*D
Symbol/data output stack
A A
+ A +
B AB +
- AB+ -
C AB+C -
* AB+C - *
D AB+CD - *
AB+CD* -
AB+CD*-
Output  A B + C D * -

ii. E*(F–G*H)
symbol output stack
E E
* E *
( E *(
F EF *(
- EF *( -
G EFG *(-*
* EFG *(-*
H EFGH *(-*
) E F G H*- *
E F G H*-* Yg kecik boleh tindan
Output  E F G H*-*

iii. P*Q/R$T
symbol output stack
P P
* P *
Q PQ *
/ PQ* /
R PQ*R /
$ PQ*R /$
T PQ*RT /$
PQ*RT$ /
PQ*RT$/
Output  P Q * R T $ /
CSC248 FUNDAMENTAL OF DATA STRUCTURES

iv. A/(B–C)*D

symbol output stack


A A
/ A /
( A /(
B AB /(
- AB /(-
C ABC /(-
) ABC- /
* ABC-/ *
D ABC-/D *
ABC-/D*
Output  A B C - / D *

b) Convert the following expression into postfix notation manually.


i. F*G$H+I–(J+K)/L
ii. P$(Q*R)+S/T–U
iii. A+B/C*D+(E–F)
iv. A*B/(C*(D+E)–F)
v. (D–E/F)*(G/H–J)

Question 2

Evaluate the following equation by using stack configuration and show all the steps involved in
solving the equation.

a) 9 + ( 2 + 3 * 2 ) / ( 4 / 2 )

b) ( 1 * 2 ) * 4 / 3
c) ((12 * 6) / (8 / 4)) * (7 – 5)

Question 3

Given an INFIX expression as follow:

A*B/(C*(D+E)–F)

i) Convert it into a POSTFIX expression

ii) Evaluate the above expression using stack. If the value of the variables are:

A = 48, B = 2, C = 3, D = 5, E = 4, F = 21
CSC248 FUNDAMENTAL OF DATA STRUCTURES

Show the diagram of the stack during the evaluation process.

Question 4

a) Convert the following prefix expression to infix notation. Show all the steps
i) + / + 9 3 2 * 5 2
symbol top stack
2 2 2
5 5 2,5
* 2*5 5*2
2 2 5*2, 2
3 3 5*2,2,3
9 9 5*2,2,3,9
+ 9+3 5*2,2,9+3
/ 9+3/2 5*2, 9+3/2
+ (5*2) +((9+3)/2) (5*2) +((9+3)/2)

ii) / * 7 + 3 5 2
symbol top stack
2 2 2
5 5 2,5
3 3 2,5,3
+ 3+5 2,3+5
7 7 2,3+5,7
* (3+5)*7 2,(3+5)*7
/ (2/(3+5)*7) (2/(3+5)*7)

iii) - * A B * / C D E
symbol top Stack
E E E
D D E,D
C C E,D,C
/ C/D E,C/D
* E*(C/D) E*(C/D)
B B E*(C/D)B
A A E*(C/D)B,A
* E*(C/D)A*B E*(C/D)A*B
- E*(C/D)-(A*B)
CSC248 FUNDAMENTAL OF DATA STRUCTURES

b) Convert the following postfix expression to infix notation. Show all the steps.

i) MN/PQ*-SK$+
symbol top stack
M M M
N N M,N
/ M/N M/N
P P M/N,P
Q Q M/N,P,Q
* P*Q M/N,P*Q
- (M/N) – (P*Q) (M/N) – (P*Q)
S S (M/N) – (P*Q),S
K K (M/N) – (P*Q),S,K
$ S$K (M/N) – (P*Q),S$K
+ ((M/N) – (P*Q))+ (S$K) ((M/N) – (P*Q)) + (S$K)

ii) A B C * D / + E –
symbol top stack
A A A
B B A,B
C C A,B,C
* B*C A,B*C
D D A,B*C,D
/ (B*C)/D A,(B*C)/D
+ A+ ((B*C)/D) A +((B*C)/D)
E E A +((B*C)/D),E
- A +((B*C)/D)) -E A +((B*C)/D)) - E

iii) 6 5 2 3 + 8 * + 3 + *
symbol top stack
6 6 6
5 5 6,5
2 2 6,5,2
3 3 6,5,2,3
+ 2+3 6,5,2+3
8 8 6,5,(2+3),8
* (2+3)*8 6,5,(2+3)*8
+ 5+(2+3)*8 6,5+(2+3)*8
3 3 6,(5+(2+3)*8),3
+ (5+(2+3)*8)+3 6,(5+(2+3)*8)+3
* 6*(5+(2+3)*8)+3 6*(5+(2+3)*8)+3

You might also like