0% found this document useful (0 votes)
33 views

Chapter 4 - Stacks and Queues

The document discusses stacks and queues as data structures. It covers stack operations like push and pop and common stack applications. It also covers queue operations like enqueue and dequeue and provides examples of array implementations of queues.

Uploaded by

ktesfaneh2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Chapter 4 - Stacks and Queues

The document discusses stacks and queues as data structures. It covers stack operations like push and pop and common stack applications. It also covers queue operations like enqueue and dequeue and provides examples of array implementations of queues.

Uploaded by

ktesfaneh2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 48

Data Structures and Algorithms

Instructor: Addis Ts.(MSc)


Email: betsega23@gmail.com
Chapter Four: Stacks and Queues
This chapter covers:
Stack
Queue

Stacks and queues are data structures that have restricted


data access, which can be accessed from end or start of the
list.

2
Stack
It is a data structure that has access to its data only
at the end or top of the list.
It operates on LIFO (last in first out) basis.
Stack uses a single pointer or (index) to keep track
of the information or data on the stack.
It has two basic operations:
Push: inserting or adding data at the top of the stack,
Pop: removing data from the top of the stack.

3

A stack of
coins

4

Push Pop
Push(5) Pop 15
……………….. Push (6) 9 12
Push(7)
………………. 7
Push (9) 6 Push(12) 6
5 Push(15) 5

12
pop 7
6
5

5
Array implementation of push and pop
operation
Analysis:
suppose the stack has the following
structure.
int num[max-size];
We need to have an integer variable that
stores an index value that tells us:
the position where to store a new value
the total number of elements stored in the
stack
int top =-1;
6
To push/add an element to the stack

Check if there is enough space in the


stack
To add new value we should have to
check the space left
top<max_size-1?
Yes – increment top , store the element in
num[top]
No – stack overflow

7
To pop or remove an element from the
stack

check if there is data in the stack


top>=0?
Yes: - copy/remove data at num[top],
decrement top
No: - stack underflow

8
Implementation – push

int num[max_size];
int top=-1;
void push(int x)
{
if (top<max_size-1)
{
top++;
num[top]=x;
}
else
cout<<“stack overflow”;
}
9
Implementation - pop
int pop()
{
int x;
if(top>=0)
{
x=num[top];
top --;
}
else
Cout<<“stack underflow”’;
return x;
} 10
Implementation ...
Size of stack
int sizeofstack()
{
return(top+1)
}
Is empty?
Bool isempty()
{
return (top==-1)
}
Is full?
Bool isFull()
{
Return(top==max_size – 1)
} 11
Linked List Implementation of Push
and Pop operations
Definition
struct number
{
int num;
Botptr
number *next;
};

Topptr

12
Analysis:
We need two pointers (Botptr and topptr) that points to first and
last node of the stack
number *botptr=NULL, *topptr=NULL;
To push data to the stack
Check if there is enough space in the stack – i.e free memory
space. We need a pointer that points to the newly created -
newnumptr = new number;
newnumptr !=NULL there is free Memory space pointed by newnumptr
Yes: - copy/store the pushed value to newly created node
Create the link between the last node and the new node….

13
(continued)…
Make topptr to point to the last node (newly created node) 
cin>>newnumptr->num; newnumptr->next=NULL;
NO: stack overflow

Botptr

newnumptr
Topptr
14
POP
Check if there is data in the stack
bottomptr!=NULL???
Yes: - topptr should point to the previous node. When we have
only one node botptr and topptr should point to NULL
Deleting the last node
No: - stack underflow

prevptr
botptr lastptr

15
Exercise
Write the complete code of stack implementation using
single linked list.

16
Application of Stack
1. Variable declaration
Void main()
{int i, n;
for (i=0;i<=10;i++)
{int m;
cin>>n;
cin>>m;
cout<<m*n;
} Used to hold
m variables when
cout<<n;
n declared
}
i

17
Application of Stack
2. function calling
Void main(){
Func1();
Func2();} Func3()
Void func1(){ Func1() Func1()
Cout<<“selam”;
Func3();
Main() Main() Main()
}
Void func2(){ 1 2 3 4
Cout<<“Hi”;
}
Void func3(){
Cout<<“Hello”; Func1() Func2()
} Main() Main() Main()
}
Note : The one that is found on 5the top of the stack
6 is currently
7 executed.
When empty stack remain, the program will halt
18
Application of Stack
3. recursive programming
int factorial (int n) Factorial(0) = 1
{ Factorial(1) = 1
if(n==0 || n==1)
Factorial(2)= 2
return (1);
else .
return(factorial(n-1)*n)
.
}
.
Factorial(n-2)
Factorial(n-1)
Factorial(n)
19
Application of Stack
Infix to postfix conversion
Infix Notation Postfix Notation prefix Notation
A+B AB+ +AB
Eg.
(A+B)*C AB+C* *+ABC
(A+B)*(C-D) AB+CD-* *(A+B)(C-D)
*+AB-CD
*+-EF,
E=AB, F=CD

20

21
Application of Stack
5. Computing Postfix Notation
AB+

+ Op=pop()
B Op1=pop()
A Op2=pop()
Result
Op2 op op1 = result
Push (result)

22

example
AB+C*
+ *
B C
A Result1 Result1 Result2

Eg. 4 5 +2* + *
5 2
4 9 18
23
Exercise
1.Write a program that convert infix to postfix notation
2. write a program that computes a given postfix notation

24
QUEUE
A queue is an ordered collection of items for which we can
only add an item at the back or remove an item from the
front.

It operates on FIFO (first in first out) basis

The queue is yet another data structure, much like a stack,


but with a much more limited set of operations.
Queue operations
It has two operations
Enqueue: adding data at the end of the list
Dequeue: deleting data at the head of the list
Eg. Enqueue(c)
Enqueue (B)
Enqueue(A) C | B| A
Dequeue()
Enqueue(D) | B| A
Dequeue() | B| A| D

A|D

26
Simple array implementation of
enqueue and dequeue
Analysis – consider the following structure
int num[max-size];

We need the following variables


int rear=-1, front=-1, queuesize=0;

27
To enqueue
Check if there is space
Queuesize<max-size or //rear< max-size?
Yes: queuesize==0?
Yes: increment front
No: Increment rear and queuesize, Store the data in data in num[rear]
No: queue overflow

28
To dequeue
Check if there is data
Queuesize>0?
Yes:
Copy the data in num[front]
Increment front
Decrement queuesize
No: queue underflow

29
example
Enqueue(5) 5
Enqueue(7) 5,7
Enqueue(4) 5,7,4
Dequeue() 7,4
Enqueue(2) 7,4,2
F R

|7|4|2

30
Exercise
Write a simple array implementation of queue data
structure ( including the operations enqueue, dequeue,
isempty, isfull, an so on)

31
Circular queue
Rear of the queue is somewhere clockwise from the front
To enqueue an element, we move rear one position clockwise
and write the element in that position
To dequeue, we simply move front one position clockwise
Queue migrates in a clockwise direction as we enqueue and
dequeue
Emptiness and fullness to be checked carefully.

32
Array implementation of Circular
Queue
Limitation of simple array implementation is, as we keep
on dequeuing an element from the array, front may exceed
maxsize, while we have some free spaces
E.g : num[5]
dequeue(), dequeue(), dequeue(), dequeue(), dequeue(),
Enqueue(3) impossible F R
5 | 7 | 6 | 11 | 8

F R
| | | |
33
Array implementation of Circular
queue

34
To enqueue

Check if there is space


Quesize<max-size??
Yes:
Queuesize==0??
Yes: increment front
Increment rear and queuesize
Rear==maxsize??
Yes: rear=0
Store the data in num[rear]

No: queue overflow

35
To dequeue
Check if there is data
Queuesize>0???
Yes:
Copy the data in num[front]
Increment front
Front==max-size??
Yes:Front=0;
Decrement queuesize
No: queue underflow

36
Exercise
Write the array implementation of circular queue data
structure

37
Linked List Implementation of
enqueue and dequeue
Enqueue – inserting node at the end of the list.
Dequeue – deleting the first node in the list.
Implementation – exercise, just see the linked list adding at
the end and deleting at the start example from the previous
chapter

38
Different types of queue
Deque:
 is also double ended queue
Insertion and deletion are possible at both ends
Implementation are the same as that of queue
Is best implemented by double linked list

Implementation: exercise

39
Priority queue
In priority queues, elements arrive in an arbitrary order,
but are enqueued with information about their priority.
It is a queue where each element has an associated key
value at the time of insertion.

40
e.g.
Original queue
Sara Solomon Ahmed Meron Abiy saba
F M M F M F

Female Queue
Sara Meron Saba

Male Queue
Solomon Ahmed Abiy
41
continued….
While (original queue is not empty)
{
Data=dequeueOriginalQueue();
If(gender of data is male)
Enqueue male queue(data);
Else
Enqueue Female queue(data)
}

42
To create priority queue
While (female queue is not empty)
Enqueue to priority queue (dequeue female queue())

While (males queue is not empty)


Enqueue to priority queue

Priority queue

Sara Meron Saba Solomon Ahmed Abiy


F F F M M M

43
e.g.2
The data with the largest element with higher
priority
A B C F E D H
40 30 25 15 18 20 12

Dequeue() A will be selected


Dequeue() B >>
Dequeue() C >>
Dequeue() D >>

44
Exercise

Write a program that merges two priority queues,


sorted in ascending order of priority, to create a single
queue.
E.g
A C D F
40 25 20 15 A B C D E F H G
40 30 25 20 18 15 12 10
B E H G
30 18 12 10

45
Application of Queue
1. printserver
Print()
{
Enqueue printqueue(document)
}

End_of_print()
{
Dequeue printqueue()
}

Document1.doc letter.doc assign.cpp

46
Application of queue
2. disk driver, the one first inserted will have first letter (eg.
A:, B:, C:, D:, E…

3. Task scheduler in multiprocessing system


Eg. Printing 16, searching 5, browsing 17, opening 7

47
Application of queue
4. Telephone calls in a busy environment
5. Simulation of waiting line
Line in a supermarket
Line at cafeteria, bank and so on…

48

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy