unit-3
unit-3
Deemed to be University
Unit-3
Stacks and Queues
What is a Stack
• Stack of Books
3
Excellence and Service
CHRIST
Deemed to be University
Stacks
• What can we do with a stack?
– push - place an item on the stack
– peek - Look at the item on top of the stack, but do not remove it
– pop - Look at the item on top of the stack and remove it
4
Excellence and Service
CHRIST
Deemed to be University
Stacks
• A stack is a LIFO (Last-In/First-Out) data structure
• A stack is sometimes also called a pushdown store.
• What are some applications of stacks?
– Program execution
– Parsing
– Evaluating postfix expressions
– Function calls
5
Excellence and Service
CHRIST
Deemed to be University
Operations of Stack
Push
Pop
Peek
Traversal (Display)
6
Excellence and Service
CHRIST
Deemed to be University
Stack
Stack overflow
Stack underflow
7
Excellence and Service
CHRIST
Deemed to be University
Push
Stack overflow
8
Excellence and Service
CHRIST
Deemed to be University
Pop
Stack underflow
9
Excellence and Service
CHRIST
Deemed to be University
Display
10
Excellence and Service
CHRIST
Deemed to be University
11
Excellence and Service
CHRIST
Deemed to be University
12
Excellence and Service
CHRIST
Deemed to be University
Push
13
Excellence and Service
CHRIST
Deemed to be University
Pop
14
Excellence and Service
CHRIST
Deemed to be University
Display
15
Excellence and Service
CHRIST
Deemed to be University
[End If]
6) END
Excellence and Service
CHRIST
Deemed to be University
Expression: 456*+
example --2
try it by yourself
231*+9-
100 200 + 2 / 5 * 7 +
46+9*
ANSWERS
1. -4
2. 757
3. 90
Try it by yourself
a+b*c
(a+b)*c+(d-a)
((4+8)(6-5))/((3-2)(2+2))
ANSWERS
a b c * +
a b + c * d a - +
4 8 + 6 5 - 3 2 - 2 2 + /
QUEUE
26
Excellence and Service
CHRIST
Deemed to be University
Operations on a Queue
27
Excellence and Service
CHRIST
Deemed to be University
enqueue
void enQueue(int value){
if(rear == SIZE-1)
printf("\nQueue is Full!!! Insertion is not possible!!!");
else{
if(front == -1&& rear==-1)
{
front = 0;
rear=0;
}
else
rear++;
queue[rear] = value;
printf("\nInsertion success!!!");
}
}
28
Excellence and Service
CHRIST
Deemed to be University
dequeue
void deQueue(){
if(front == -1 && rear==-1)
Display
void display(){
if(rear == -1)
printf("\nQueue is Empty!!!");
else{
int i;
printf("\nQueue elements are:\n");
for(i=front; i<=rear; i++)
printf("%d\t",queue[i]);
}
}
30
Excellence and Service
CHRIST
Deemed to be University
Drawbacks of queue
31
Excellence and Service
CHRIST
Deemed to be University
Circular queue
● Modulo arithmetic
● Queue full
○ Case 1 full
○ Case 2 empty
○ Few elements
● Queue empty
○ Case 1 empty
○ Case 2 one element
○ Few elements
32
Excellence and Service