Stacks
Stacks
Presented by:
Dr. Ishleen Kaur
Table of Contents
• Introduction to Stacks
• Array Implementation of Stacks
• Operations on Stacks
• Applications of Stacks
• Linked List Implementation of Stacks
Stacks
Push 11
void push (STK *s, int item)
{
if(is_full(s) )
{
printf(“Overflow”);
exit();
}
top++;
a[top] = item;
}
Push operation
Push 6
void push (STK *s, int item)
{
if(is_full(s) )
{
printf(“Overflow”);
exit();
}
top++;
a[top] = item;
}
Pop operation
Pop
int pop (STK *s)
{
if (is_empty(s) )
{
printf(“Underflow”);
exit();
}
x= a[top]
top--;
return (x);
}
Copy the elements from stack S1 to stack S2 using intermediate
stack.
3 1 1
2 2 2 2 2
1 1 3 1 3 3 3
Pop(temp) Push (S2,1) Pop(temp) Push(S2,2) Pop(temp) Push(S2,3) temp S2
3 3
2 2 2 2
3 1 3 1 1 1
Applications of Stack
Expression
Prefix or Postfix or
Infix
Polish Reverse Polish
a*b
*ab ab*
Convert 3+4*5-6/3+(2-3) into postfix expression.
3+4*5-6/3+(23-)
3+(45*) - 6/3+ (23-)
3+(45*) - (63/) + (23-)
(345*+) - (63/) + (23-)
(345*+ 63/-) + (23-)
345*+63/-23-+
7 – 3 + 6 * 2 + ( 5+2) / 2
7-3+6*2+(52+)/2
7-3+(62*)+(52+)/2
7-3+(62*)+(52+2/)
(73-)+(62*)+(52+2/)
(73-62*+)+(52+2/)
73-62*+52+2/+
Convert 3+4*5-6/3+(2-3) into prefix expression.
3+4*5-6/3+(-23)
3 + (*45) – (/63) + (-23)
(+3*45) – (/63) + (-23)
(-+3*45 /63) + (-23)
+ -+3*45 /63 -23
7 – 3 + 6 * 2 + ( 5+2) / 2
7-3+6*2+(+52)/2
7-3+(*62)+(+52)/2
7-3+(*62)+(/+522)
-73+(*62)+(/+522)
(+-73*62)+(/+522)
++-73*62/+522
Evaluate 2*3+(4+5) using stack
Operator Stack
*
*
5 +
3 4 4 9 +(
2 2 6 6 6 6 15 +(+
+
Operator stack
+
( (
* * + + + +
Question: Evaluate 2*5*(3+6) using stack
Evaluate 2*5*(3+6) using stack
Operator Stack
*
*
6 *
5 3 3 9 *(
2 2 10 10 10 10 90 *(+
*
Operator stack
+
( (
* * * * * *
Evaluate 25*36+* using stack
6
5 3 3 9
2 2 10 10 10 10 90
Operator stack
* + *
Question: Evaluate 5+3*(6/2) using stack