0% found this document useful (0 votes)
6 views30 pages

10 DS Queue

Uploaded by

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

10 DS Queue

Uploaded by

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

Data Structures

CT077-3-2- DSTR and Version VC1

Queues
Topic Structure

• Definition
• Application
• Operation
• Implementation

CT077-3-2-DSTR Data Structures 2


Objectives

By the end of this lesson, you will be able to:

• Understand the concept of a queue data structure


• Examine and implement queue operations
• Discover applications where queues are useful

CT077-3-2-DSTR Data Structures 3


Key terms

• First in first out (FIFO)


• enqueue()
• dequeue()
• Circuar queue

CT077-3-2-DSTR Data Structures 4


Queue Data Structure

• A queue is a list of homogeneous elements which get


• Added at one end (the back or rear)
• Deleted from the other end (the front)

Bus
Stop

front
rear

• Called a FIFO data structure (First In First Out)


• Middle elements are inaccessible
CT077-3-2-DSTR Data Structures 5
Queue Applications

• Implementing a waiting line


– For a bank reception system, books reservation in a library
system, printing jobs of a shared printer, processes
competing on resources in operating system, server
handling clients requests, etc.

• Some real life queues are not exactly FIFO


– Removal from a queue may be done by priority rather than
by arrival time order (called priority queues)
– Boarding into a plane: first class, frequent flyers, economic
– Treatment in a hospital: emergency cases, normal patients
– Threads with higher priority for critical OS tasks
CT077-3-2-DSTR Data Structures 6
Queue Operations

• Standard operations:
• addQueue… adds an element to queue’s rear
• deleteQueue… deletes element from queue’s
front and returns it
• isEmpty … returns true iff queue is empty
• Additional operations:
• front… returns the front element of the queue
(without removing it)
• rear… returns the rear element of the queue
(without removing it)

CT077-3-2-DSTR Data Structures 7


Queue Data Structure Representation

• Using Arrays
– Use a 1D array (static or dynamic), size is fixed
– Elements are added using a front index
– Elements are removed using a rear index

• Using Linked Lists


– Elements are stored inside linked nodes
– Elements are added at the end of the list (using
a tail pointer)
– Elements are removed from the beginning (using
head pointer)
CT077-3-2-DSTR Data Structures 8
Implementing Queue using Array

Four data members:


• An array to store queue elements template <class T>
class Queue{
• Variable queueFront to keep
track of first queue element index T * list;
int maxQueueSize;
• Variable queueRear to keep track int queueFront;
int queueRear;
of last queue element index
• Variable maxQueueSize to specify public:
Queue(int maxSize)
maximum queue size (array size) { ... }
~Queue() { ... }
void addQueue(T elem)
{ ... }
T deleteQueue(){ ... }
bool isEmpty(){ ... }
};

CT077-3-2-DSTR Data Structures 9


Implementing Queue using Array

Example: array size is 100; originally empty


• Initialize: queueRear = -1; queueFront= 0;
• To add an element to the queue:
– Advance queueRear to next array position
– Add element at index pointed by queueRear
q.addQueue('A')
;
q.addQueue('B')
;
q.addQueue('C')
;

CT077-3-2-DSTR Data Structures 10


Array Implementation: deleteQ

• To delete an element from the queue:


– Retrieve element pointed to by the index queueFront
– Advance queueFront to point to the next index of queue
element

q.deleteQueue()
;

CT077-3-2-DSTR Data Structures 11


Array Implementation: Full Tank!?

• Will this queue design work?


• When queue rear index reaches end of the array,
does this mean the queue is full?

• Solution 1: When queue overflows to the rear and


front indicates available slots, shift all elements to
the beginning of the array
– Problem: too slow for large queues

CT077-3-2-DSTR Data Structures 12


Array Implementation: Circular Array

• Solution 2: Assume that the array is circular


– Conceptually, i.e. change indices in a circular way
queueRear = (queueRear + 1) %
maxQueueSize;
queueFront = (queueFront + 1) %
maxQueueSize;

q.addQueue('Z')
;

CT077-3-2-DSTR Data Structures 13


q.deleteQueue() Queue becomes empty
;

Problem: two different


cases with identical
values for queueFront
and queueRear

q.addQueue('Z') Queue becomes full


;

CT077-3-2-DSTR Data Structures 14


Array Implementation: Empty or Full?

• How to determine if the queue is empty?


bool isEmpty(){
if (queueRear == queueFront-1)
return true;//not correct necessarily; maybe
full!
else
return false;
}
• Solution 1: Define a boolean variable lastOpAddQ
• In addQueue set this variable to true
• In deleteQueue set it to false
• Empty iff (queueRear == queueFront-1) && ! lastOpAddQ
• Full iff (queueRear == queueFront-1) && lastOpAddQ

CT077-3-2-DSTR Data Structures 15


Array Implementation: Empty or Full?

• Solution 2: use count variable


– Initialized to zero
– Incremented when a new element is added to
the queue
– Decremented when an element is removed
– Compare it to zero or maxQueueSize to
determine queue bring empty or full
– Very useful if there is frequent need to know
the number of elements in the queue

CT077-3-2-DSTR Data Structures 16


Exercise

• Implement the class QueueArray according to the


explanations given so far
template <class T>
class QueueArray{

T * list;
Indicates a default value, i.e.
int maxQueueSize;
int queueFront;
if constructor is not passed
int queueRear; any value, 100 will be used
int count; as value for maxSize

public:
QueueArray(int maxSize = 100)
{ ... }
~QueueArray() { ... }
void addQueue(T elem) { ... }
T deleteQueue() { ... }
bool isEmpty() { ... }
int size() { ... }
};
CT077-3-2-DSTR Data Structures 17
Exercise Solution

• Constructor and Destructor


QueueArray(int maxSize = 100) {
if (maxSize <= 0){
cout << "Queue size must be positive, not " << maxSize <<
endl;
abort();
}
list = new T[maxSize];
maxQueueSize = maxSize;
queueFront = 0;
queueRear = -1; //can also be: queueRear = maxSize -1;
count = 0;
}

~QueueArray() {
delete [] list;
}

CT077-3-2-DSTR Data Structures 18


Exercise Solution – cont.

• Size and Empty

bool isEmpty() {
return (count == 0);
}

int size() {
return count;
}

CT077-3-2-DSTR Data Structures 19


Exercise Solution – cont.

• Add and Delete


void addQueue(T elem) {
if (count < maxQueueSize) {
queueRear = (queueRear + 1) % maxQueueSize;
list[queueRear] = elem;
count++;
}
else
cout << "Cannot add, queue is full now." << endl;
}
T deleteQueue() {
if ( isEmpty() ) {
cout << "Cannot delete from an empty queue." << endl;
abort();
}
int frontIndex = queueFront;
queueFront = (queueFront + 1) % maxQueueSize;
count--;
return list[frontIndex];
}
CT077-3-2-DSTR Data Structures 20
Exercise Solution – cont.

• Main driver function to test queue functionalities


void main() {
QueueArray<int> q(10);

cout << "Add and delete few elements to advance queueRear:" <<
endl;
q.addQueue(1); q.addQueue(2); q.addQueue(3);
cout << q.deleteQueue() << endl;
cout << q.deleteQueue() << endl;

cout << "Enter numbers to add to the queue, -1 to stop:" <<


endl;
int x; cin >> x;
while ( x != -1 ){
q.addQueue(x);
cin >> x;
}
cout << "Going to delete all queue elements:" << endl;
while ( ! q.isEmpty() )
cout << q.deleteQueue() << endl;
CT077-3-2-DSTR
system("pause"); Data Structures 21
Linked Implementation of Queues

• Array implementation issues


– Array size is fixed: only a finite number of queue
elements can be stored in it
• The array implementation of the queue requires
array to be treated in a special way (circular)

• The linked implementation of a queue simplifies


many of the special cases of array implementation
– In addition, the queue never gets full (in theory)

CT077-3-2-DSTR Data Structures 22


Linked Nodes Implementation of
Queues
• Elements are added at one end and removed
from the other
– We need to know the front of the queue and
the rear of the queue
• Elements are added at the end of the list using a
queueRear pointer (i.e. tail of the list)
– Similar to insertAtEnd() of linked list
• Elements are removed from the beginning using
queueFront pointer (i.e. head of the list)
– Similar to deleteFirst() of linked list
CT077-3-2-DSTR Data Structures 23
Queues using Linked Nodes
• Use the following for queue implementation
template <class T>
class NodeType {
public:
T info;
NodeType<T> * link;
};
template <class T>
class Queue{
NodeType<T> * queueFront; //queue’s first node (head)
NodeType<T> * queueRear; //queue’s last node (tail)
int count; //to keep track of number of elements in the queue
public:
Queue() { ... } //constructor
~Queue() { ... } //destructor
void addQueue(T elem){ ... } //adds new node to the end of the
queue
T deleteQueue(){ ... } //deletes the first node and returns its
info
bool isEmpty(){ ... } //true if queue is empty, false otherwise
int size(){ ... } //returns the
CT077-3-2-DSTR
number of elements stored in the
Data Structures 24
Test Preparation

• Implement Queue methods to evaluate your


capability to answer test questions
• Use a main function to test your implementation
void main() {
Queue<string> q2;
string word;
cout << "Input a sentence ending with space-period ( .) :" <<
endl ;
cin >> word;
while ( word != "." ){
q2.addQueue(word);
cin >> word;
}
cout << "Breaking down the sentence into its words:" << endl;
while ( ! q2.isEmpty() )
cout << q2.deleteQueue() << endl;
system("pause");
}
CT077-3-2-DSTR Data Structures 25
Additional Resources - VisuAlgo

• visualgo.net project provides interactive tools to


help students better understand the working of
fundamental data structures and algorithms
• It allows learners to learn the basics, visually trace
algorithms execution, interact with the system, and
follow steps at their own pace
• It has automated question generator and verifier
(online quiz system) that allows learners to test their
knowledge of basic data structures and algorithms

CT077-3-2-DSTR Data Structures 26


Exercise

• Write a C++ program to simulate a queue


management system in a Bank using
linked list. The program must contain the
following functionalities :
– Register customer into the queue system.
– Calling the customer.
– Show the list of waiting customers.

CT077-3-2-DSTR Data Structures 27


Summary of Main Teaching

• Definition
• Application
• Operation
• Implementation

CT077-3-2-DSTR Data Structures 28


CT077-3-2-DSTR Data Structures 29
What will we cover next

• Tree
– Definition and notation
• Binary Tree
– Definition
– Properties
– Representation

CT077-3-2-DSTR Data Structures 30

You might also like