You are on page 1of 72

DATA STRUCTURE USING C ++

CHAPTER 6:
QUEUES
MOHAMED HASSAN ABDULLE
HORMUUD UNIVERSITY
EMAIL: JALAQSANE2003@GMAIL.COM
FACEBOOK: MOHAMED HASSAN UGASKA
Mobile: +252615825152 Or +252615000196
HTTP://HU.EDU.SO/
Course Name: Data Structure Lecturer : Eng . Ugaska
Chapter Objectives

 Objectives

 In this chapter, you’ll learn


 Introduction to queues
 Operations Performed on queues.
 Queues Implementation.
 Circular queue
 Deque
 Priority Queues
Slide 1- 2
Diagram
Introduction to Queues
 Like Stack, Queue is a linear structure which follows
a particular order in which the operations are
performed. 
 The order is First In First Out (FIFO).  A good
example of queue is any queue of consumers for a
resource where the consumer that came first is
served first.
The difference between stacks and queues is in
removing. In a stack we remove the item the most
recently added; in a queue, we remove the item the
least recently added.
Operations on Queue:
 Mainly the following four basic operations are
performed on queue:
 Enqueue: Adds an item to the queue. If the queue is
full, then it is said to be an Overflow condition.
Dequeue: Removes an item from the queue. The
items are popped in the same order in which they
are pushed. If the queue is empty, then it is said to
be an Underflow condition.
Front: Get the front item from queue.
Rear: Get the last item from queue.
Data Structure and Algorithms - Queue
 Queue is an abstract data structure, somewhat
similar to Stacks. Unlike stacks, a queue is open
at both its ends. One end is always used to insert
data (enqueue) and the other is used to remove
data (dequeue). Queue follows First-In-First-Out
methodology, i.e., the data item stored first will
be accessed first.
Queue Representation
 As we now understand that in queue, we access
both ends for different reasons. The following
diagram given below tries to explain queue
representation as data structure −
Queues
 1. queue is an algorithm
 2. Data structure
 3. Linear Data structure
 4. FIFO manner
In real life queues form at many places such as cafeterias,
petrol stations, shopping centers, anyplace where many
people line up for few resources.
 Queue is based on FIFO (First in First Out) Stores a set of
elements in a particular order
 Queue principle: FIRST IN FIRST OUT = FIFO
 It means: the first element inserted is the first one to be
removed
Basic Operations
 Queue operations may involve initializing or defining the
queue, utilizing it, and then completely erasing it from the
memory. Here we shall try to understand the basic
operations associated with queues −
 enqueue() − add (store) an item to the queue.
 dequeue() − remove (access) an item from the queue.
 Few more functions are required to make the above-
mentioned queue operation efficient. These are −
peek() − Gets the element at the front of the queue without removing it.
 isfull() − Checks if the queue is full.
 isempty() − Checks if the queue is empty.
Queue Operations
Front = -1
Rear = -1
  Fig. 1. Queue is empty .
Front

10 Front = 0
Rear = 0

Rear Fig. 2. Push (10)

Front
10 3 Front = 0
Rear = 1
Fig. 3. Push (3)
Rear
Stack examples
What is Queues?
Definition
 Queue is a linear data structure that permits insertion of
new element at one end and deletion of an element at
the other end.
 The end at which insertion of a new element can take
place is called ‘ rear ‘ and the end at which deletion of an
element take place is called ‘ front ‘.
 Front and rear are also called head and tail respectively.
 The first element that gets added into queue is the first
one to get removed from the list, Hence Queue is also
referred to as First-In-First-Out ( FIFO ) list.
Cont…….
 In computer science, queuing refers to lining up 
jobs for a computer or device. For example, if you
want to print a number of documents, the 
operating system (or a special print spooler)
queues the documents by placing them in a
special area called a print buffer or print queue. 
 The printer then pulls the documents off the
queue one at a time.
 Another term for this is print spooling .
 The order in which a system executes jobs on a
queue depends on the priority system being used.
Queues

Queues 14
Queues

12 69 50 32 78 88

rear front

rear front Computer Implementation


A waiting queue of queue

15
Queue Applications
 Real life examples
 Waiting in line
 Applications related to Computer Science
 Threads: way for a program to divide split itself into two or more simultaneously
running tasks.

 Job scheduling (e.g. Round-Robin algorithm for


CPU allocation)
- Event queuing: A queue that contain events inside.
-Message Queuing: is a software used for inter process
communication meaning that the sender and receiver of the message do not need
to interact with the message queue at the same time.
Queue Operations
 The basic operations that can be performed on
queue are:
 Enqueue : add an element to the tail of a queue
 Dequeue : remove an element from the head of a
queue
 first : examine the element at the head of the
queue (“peek”)
 Other useful operations (e.g. is the queue empty)
 It is not legal to access the elements in the middle
of the queue!
Enqueue Operation
 Enqueue/push: operation will insert (or add) an element to queue, at the rear
end, by incrementing the array index.
 Queues maintain two data pointers, front and rear. Therefore, its operations are
comparatively difficult to implement than that of stacks.
 The following steps should be taken to enqueue (insert) data into a queue .
 Step 1 − Check if the queue is full.
 Step 2 − If the queue is full, produce overflow error and exit.
 Step 3 − If the queue is not full, increment rear pointer to point the next empty space.
 Step 4 − Add data element to the queue location, where the rear is pointing.
 Step 5 − return success.

Dequeue Operation
 Dequeue/pop: operation will delete (or remove) from the front end by decrementing
the array index and will assign the deleted value to a variable.
 Accessing data from the queue is a process of two tasks − access the data where front is
pointing and remove the data after access. The following steps are taken to
perform dequeue operation −
 Step 1 − Check if the queue is empty.
 Step 2 − If the queue is empty, produce underflow error and exit.
 Step 3 − If the queue is not empty, access the data where front is pointing.
 Step 4 − Increment front pointer to point to the next available data element.
 Step 5 − Return success.
Other Examples
First In First Out

D rear
C rear C D rear
rear B B C
rear B
A front A front A front B front
front A
Queue can be implemented in two ways:
 1. Using arrays (static)
 2. Using pointers (dynamic)
 Implementation of queue using pointers will be
discussed in later chapter . Let us discuss
underflow and overflow conditions when a queue
is implemented using arrays.
 If we try to pop (or delete or remove) an element
from queue when it is empty, underflow occurs. It
is not possible to delete (or take out) any element
when there is no element in the queue.
ALGORITHM FOR QUEUE
OPERATIONS
 Let Q be the array of some specified size say SIZE
 INSERTING AN ELEMENT INTO THE QUEUE
 1. Initialize front=0 rear = –1
 2. Input the value to be inserted and assign to variable “data”
 3. If (rear >= SIZE)
 (a) Display “Queue overflow”
 (b) Exit
 4. Else
 (a) Rear = rear +1
 5. Q[rear] = data
 6. Exit
DELETING AN ELEMENT FROM QUEUE
 1. If (rear< front)
 (a) Front = 0, rear = –1
 (b) Display “The queue is empty”
 (c) Exit
 2. Else
 (a) Data = Q[front]
 3. Front = front +1
 4. Exit
Simple example of queue in C++
 #include<iostream>

 using namespace std;

 #define MAX 50

 int queue_arr[MAX];

 int rear = -1;

 int front = -1;


 //This function will insert an element to the
queue
 void insert ()
 {
 int added_item;
 if (rear==MAX-1)
 {
 cout<<"\nQueue Overflow\n."<<endl;
 return;
 }
 else
 {
 if (front==-1) /*If queue is initially empty */
 front=0;
 cout<<"\nInput the element for adding in queue";
 cin>>added_item;
 rear=rear+1;
 //Inserting the element
 queue_arr[rear] = added_item ;
 }
 }/*End of insert()*/
 void del()

{

 if (front == -1 || front > rear)

{

 cout<<"\nQueue Underflow\n";

 return;

}
 else
 {
 //deleteing the element
 cout<<"\nElement deleted from queue is : %d\n";
 queue_arr[front];
 front=front+1;
 }
 }/*End of del()*/
 void display()
 {
 int i;
 //Checking whether the queue is empty or not
 if (front == -1 || front > rear)
 {
 cout<<"\nQueue is empty\n";
 return;
 }
 else
 {
 cout<<"\nQueue is :\n";
 for(i=front;i<= rear;i++)
 cout<<queue_arr[i];
 cout<<"\n";
 }
 }/*End of display() */
 int main()
 {
 int choice;
 while (1)
 {
 //Menu options
 cout<<"\n1.Insert\n";
 cout<<"\n2.Delete\n";
 cout<<"\n3.Display\n";
 cout<<"4.Quit\n";
 cout<<"\nEnter your choice:";
 cin>>choice;
 switch(choice)
 {
 case 1 :
 insert();
 break;
 case 2:
 del();
 break;
 case 3:
 display();
 break;
 case 4:

 exit(1);

 default:

 cout<<"\n Wrong choice\n";

 return 0;

 }/*End of switch*/

 }/*End of while*/

 }/*End of main()*/
OTHER QUEUES

There are three major variations in a simple queue.


They are:
1. Circular queue
2. Double Ended queue (de-queue)
3. Priority queue
CIRCULAR QUEUE
 In circular queues the elements Q[0],Q[1],Q[2] ....
Q[n – 1] is represented in a circular fashion with
Q[1] following Q[n].

 A circular queue is one in which the insertion of a


new element is done at the very first location of
the queue if the last location at the queue is full.
 This queue is not linear but circular.
Real life example: of circular queue is Burning DVD
When burning DVD it is essential that the laser
beam burning pits on to the surface is constantly
fed with data, other wise the DVD fails.
 Suppose Q is a queue array of 6 elements. Push
and pop operation can be performed on circular.
The following figures will illustrate the same.
 After inserting an element at last location Q[5],
the next element will be inserted at the very first
location (i.e., Q[0]) that is circular queue is one in
which the first element comes just after the last
element.
• In circular queue, once the Queue is full the
"First" element of the Queue becomes the
"Rear" most element, if and only if the "Front"
has moved forward. otherwise it will again
be a "Queue overflow" state.
At any time the position of the element to be
inserted will be calculated by the relation Rear =
(Rear + 1) % SIZE.
After deleting an element from circular queue the
position of the front end is calculated
by the relation Front= (Front + 1) % SIZE.

After locating the position of the new element to


be inserted, rear, compare it with front. If (rear =
front), the queue is full and cannot be inserted
anymore.
45
46
DEQUES
 The name deque is short for "double ended
queue" and is usually pronounced "deck". 
 It Allows elements to be added or removed on
either the ends.
DEQUES
A deque is a homogeneous list in which elements
can be added or inserted (called push operation)
and deleted or removed from both the ends
(which is called pop operation).
we can add a new element at the rear or front
end and also we can remove an element from
both front and rear end. Hence it is called Double
Ended Queue.
Types of deque
 There are two types of deque depending upon
the restriction to perform insertion or deletion
operations at the two ends. They are:
 1. Input restricted deque: is one where deletion
can be made from both ends, but insertion can be
made at one end only.
 2. Output restricted deque: is one where
insertion can be made at both ends, but deletion
can be made from one end only.
Double Ended Queue Datastructure
 Double Ended Queue is also a Queue data
structure in which the insertion and deletion
operations are performed at both the ends
(front and rear).
 That means, we can insert at both front and rear
positions and can delete from both front and rear
positions.
Double Ended Queue can be represented in TWO ways,
those are as follows...
 nput Restricted Double Ended Queue
 Output Restricted Double Ended Queue
 Input Restricted Double Ended Queue
 In input restricted double-ended queue, the
insertion operation is performed at only one end
and deletion operation is performed at both the
ends.
Double Ended Queue can be represented in TWO ways,
those are as follows...
 Output Restricted Double Ended Queue
 In output restricted double ended queue, the
deletion operation is performed at only one end
and insertion operation is performed at both the
ends.
OPERATIONS IN DEQUE
 The possible operation performed on deque is
 1. Add an element at the rear end
 2. Add an element at the front end
 3. Delete an element from the front end
 4. Delete an element from the rear end
Only 1st, 3rd and 4th operations are performed by
input-restricted deque and 1st, 2nd and 3rd
operations are performed by output-restricted
deque.
PRIORITY QUEUE
Priority Queue
 Priority Queue is more specialized data structure
than Queue. Like ordinary queue, priority queue
has same method but with a major difference.
 In Priority queue items are ordered by key value
so that item with the lowest value of key is at front
and item with the highest value of key is at rear or
vice versa.
 So we're assigned priority to item based on its key
value.
 Lower the value, higher the priority. Following are
the principal methods of a Priority Queue.
PRIORITY QUEUE
Priority Queue is a queue where each element is
assigned a priority. In priority queue, the
elements are deleted and processed by following
rules.

1. An element of higher priority is processed


before any element of lower priority.
 2. Two elements with the same priority are
processed according to the order in which they
were inserted to the queue.
Basic Operations
 Basic Operations
 insert / enqueue − add an item to the rear of the queue.
 remove / dequeue − remove an item from the front of
the queue
 Priority Queue Representation
Cont..
 We're going to implement Queue using array in
this article. There is few more operations
supported by queue which are following.
 Peek − get the element at front of the queue.
 isFull − check if queue is full.
 isEmpty − check if queue is empty.
Insert / Enqueue Operation
 Whenever an element is inserted into queue,
priority queue inserts the item according to its
order. Here we're assuming that data with high
value has low priority.
Remove / Dequeue Operation
 Whenever an element is to be removed from queue,
queue get the element using item count. Once
element is removed. Item count is reduced by one.
 For example, Consider a manager who is in a
process of checking and approving files in a first
come first serve basis. In between, if any urgent
file (with a high priority) comes, he will process
the urgent file next and continue with the other
low urgent files.
 Above Fig. gives a pictorial representation of
priority queue using arrays after adding 5
elements
 (10,14,12,60,13) with its corresponding priorities
(9,10,17,30,46). Here the priorities of the data(s)
are in ascending order. Always we may not be
pushing the data in an ascending order.
 A priority queue, like a dictionary, contains
_entries_ that each consist of
 a key and an associated value. However,
whereas a dictionary is used when we
 want to be able to look up arbitrary keys, a
priority queue is used to
 prioritize entries. Define a total order on
the keys (e.g. alphabetical
 order). You may identify or remove the
entry whose key is the lowest (but no
 other entry).
 This limitation helps to make priority
queues fast. However, an
 entry with any key may be inserted at any
time.
  
Applications of Priority Queues
Many, many applications.
Scheduling queues for a processor, print queues { 
all the work that has yet to be completed}, etc.….
This means this item will be in the front of queue
“Obtained” via a remove().

Note: a priority queue is no longer FIFO!


You will still remove from front of queue, but
insertions are governed by a priority.
Priority Queues
Operations performed on priority queues
1) Find an element,
2) Insert a new element
3) Delete an element, etc.
Two kinds of (Min, Max) priority queues exist:
 In a Min priority queue, find/delete operation
finds/deletes the element with minimum priority
 In a Max priority queue, find/delete operation
finds/deletes the element with maximum priority
 Two or more elements can have the same priority
priority queue Implementation
 A priority queue can be implemented using many
of the data structures that we've already studied
(an array, a linked list, or a binary search tree).
Elements Priority
Example
27 4
11 2
10 1
20 3
15 6
12 5
Solutions
Elem 10 11 20 27 12 15
Pri 1 2 3 4 5 6
Conclusion
 Conclusion
 Priority queues are nothing but the extension of the
queue. But unlike queues which add/remove items using
the FIFO approach, in priority queue the items are
removed from the queue according to the priority. Thus
each item in the queue is associated with a priority and
the item with the highest priority is the first one to be
taken off the queue.
 The priority queue has three main operations i.e. insert
(), getHighestPriority () and deleteHighestPriority ().
Priority queue can be implemented using arrays or
linked list
Data Structure

Questions
?

INSTRUCTOR : MOHAMED HASSAN ABDULLE COURSE :DATA STRUCTURE USING C ++


DATA STRUCTURE USING C ++

INSTRUCTOR : MOHAMED HASSAN ABDULLE COURSE :DATA STRUCTURE USING C ++

You might also like