Stacks and Queues
Stacks and Queues
Implementation
1. PUSH
stack[++*top]=item;
}
2. POP
1. ADD
queue[++*rear]=item;
}
2. DELETE
CIRCULAR QUEUES
Initially front=rear=0
Discuss examples
Implementation
INSERT FRONT
DELETE REAR
AB$C*D-EF/GH+/+
Prefix
A$B*C-D+E/F/+GH
$AB*C-D+E/F/+GH
*$ABC-D+E/F/+GH
*$ABC-D+/EF/+GH
*$ABC-D+//EF+GH
-*$ABCD+//EF+GH
+-*$ABCD//EF+GH
ii. ((A+B)*C-(D-E))$(F+G)
Postfix: AB+C*DE--FG+$
Prefix: $-*+ABC-DE+FG
iii. A-B/(C*D$E)
Postfix: ABCDE$*/-
Prefix: -A/B*C$DE
iv. A/B-C+D*E-A*C
v. A+(((B-C)*(D-E)+F)/G)$(H-J)
Applications of Stacks
Evaluation of expressions
In order to evaluate a postfix expression we use a stack
Ex: Infix 6/2-3+4*2
Postfix 6 2 /3 – 4 2 * +
Token Stack top
[0] [1] [2]
6 6 0
2 6 2 1
/ 6/2 0
3 6/2 3 1
- 6/2-3 0
4 6/2-3 4 1
2 6/2-3 4 2 2
* 6/2-3 4*2 1
+ 6/2-3+4*2 0
int eval(void){
token t;
char symbol;
int op1, op2;
int n=0;
int top=-1;
t=get_token(&symbol l, &n);
while(t!=eos)
{
if(t==operand)
PUSH(&top, symbol-‘0’);
else
{
op2=POP(&top);
op1=POP(&top);
switch(t){
case plus: PUSH(&top, op1+op2);break;
case minus: PUSH(&top, op1-op2);break;
case multiply: PUSH(&top, p1*op2);break;
case divide: PUSH(&top, op1/op2);break;
case mod: PUSH(&top, op1%op2);break;
}
}
t=get_token(&symbol, &n);
}
return POP(&top);
}
If the operator is left associative, i/p precedence is less than the stack
precedence and if an operator is right associative, i/p precedence is higher
than the stack precedence.
Initial configuration
Final configuration