Sie sind auf Seite 1von 12

DS DSAA ( Common Topics )

3. Queues
Queue is an ordered collection of elements from which elements may be deleted (i.e.
removed) from one end (called Front end of the queue) and elements may be inserted
at the other end (called Rear end of the queue).
The element that comes first in the queue is removed first thus Queue is also called
FIFO (First In First Out) list.

The Queue ADT :


The Queue ADT uses some container to hold multiple elements in a sequence. Also,
it holds pointers (i.e. two variables) to keep track of front and rear end of the queue.
Also, addition of elements is from Front end and removal is done from the Rear end
of the list. i.e. FIFO principle.
It supports following common operations.
Enqueue( elmt ): i.e Insert Element : Insert element at the end (rear) of the queue.
Input: Element ; Output : None
Dequeue() : i.e. Remove Element : Remove and return an element at the front end
of
the queue i.e. remove first element in the queue.
Input: None ; Output : Element
Display() : Display all the elements in the queue from first to last.
Input: None ; Output : None
We can also define following additional operations.
Size() : returns the number (count) of elements in the queue.
Input: None ; Output : integer
IsEmpty() : returns Boolean ; true (i.e. 1) if queue is empty and false if queue has
elements.
Input: None ; Output : Boolean
Front() : Returns front (not remove)object in the queue; error occurs if queue is
empty.

Array implementation of Queue:


In this implementation an array is used to hold the queue elements. Two variables
front and rear are used to hold the positions of first and last element within the
array. Lets create a data structure that is used as a queue of integers.
a

front

...
0

n-1

-1
-1

rear
Figure 1-a shows an empty queue. The next figure 1-b shows a queue after adding
three elements A, B and C to the queue. In this case q.rear=2 and q.front=0. The last
figure 5.1-c shows a queue after removing elements A and B from the queue.
Prepared by, Santosh Kabir
Mobile: 98336 29398

1 of 12

3.Queues
www.santoshkabirsir.com

DS DSAA ( Common Topics )

0
1
2
.
.

SIZE-1

front= -1

A
B
C
.
.

C
.
.

front = 0

front =2

1-a
1-b
1-c
If array size is 8 then at time queue can store maximum 8 elements. Suppose, as we go on adding and removing
elements from the queue, a situation arrives where rear is 7 and front is at any position, say, 3 then further addition
of an element will generate queue overflow error. In this case actually queue is not full since the first 3 elements
are already removed from the queue.
One solution to this is to modify the remove operation. Assume there are total n elements present in a queue.
Whenever an element is removed from a queue, shift all the elements towards the front of the queue so that front
is always at position 0. The method is too inefficient since each removal of an element involves moving all the n-1
elements in the queue. If queue contains thousands of elements then its really very inefficient way of using a
queue.
The best solution to this problem is to consider a circular queue (the topic that we will discuss later in this chapter).
Note: We will consider front= -1 and rear= -1 at the beginning.

1. Linear Queue:
Elements are added into array one after other.
As last element of array is filled, queue becomes full. Adding further elements to
Queue is not permitted.
Different operations with their algorithms are mentioned below :

Empty queue:
Function returns true (i.e. 1 ), if queue has no elements.
A-1
Algo: Empty( )
1. If front= -1 then
a. Return 1
2. Else
a. Return 0

Full Queue:
This condition arises when the rear end item exists at the last element of the array
created for storing the queue items. The function can be written as follows that
returns true if queue is full.
A-2
Algo: FullQueue( )

Prepared by, Santosh Kabir


Mobile: 98336 29398

2 of 12

3.Queues
www.santoshkabirsir.com

DS DSAA ( Common Topics )


1. If rear end pos. = Array size 1 then
a. Return 1
2. Else
b. Return 0

Adding an element to a queue (Enqueue) :


A new item can be added at the rear end of the queue.
A-3
Algo: AddItem( element )
1. If queue is full
a. Display error message
2. Else
a. Increment rear-end pos. by 1
b. Put the element at the new rear-end position.

The above algorithm is applicable for array implementation of a queue, since we


have limited storage space (size of array). In linked-list implementation of a
queue, the full queue condition will arise when a computer can not allocate
memory for a new item.

Removing an element from a Queue (Dequeue ) :


Items can be removed from front of a queue. Whenever an item is removed from a
queue, the front of queue advances by one position i.e. next element becomes front.
An algorithm for a function remove() to remove queue item is as given below.
A-4
Algo: RemoveItem( )
1. Read the front end item in a variable (say m)
2. Increment front pos. by 1
3. If front pos. goes beyond rear pos.
a.
Indicate queue is empty
(i.e. make front and rear = 1)
4. Return the item read from front end (i.e. m)

Remember that a function remove() should be called only if the queue is not
empty.

Displaying a queue:
Displaying queue is printing array elements from fe to re index, if queue is not empty.
A-5
Algo: ShowQueue( )
1. If queue is empty
Print queue is empty
1. Else
i. Read the front end position of queue.
Ii While rear end is not reached repeat following
a. Display data at the current position

Prepared by, Santosh Kabir


Mobile: 98336 29398

3 of 12

3.Queues
www.santoshkabirsir.com

DS DSAA ( Common Topics )


b. Advanced to next position.

Program for Queue using array :


#include<stdio.h>
#include<conio.h>
#define Size 8
struct Queue
{
int a[Size]; // Array to hold queue elements
int fe, re;
// index var. for front and rear ends
};
// Global var. for Queue operations

struct Queue q;
int IsEmpty(void);
int IsFull(void);
void Add( int v );
int Remove(void);
void Display(void);
int Front(void);
int IsEmpty() // returns 1 if Queue is empty
{
return q.fe == -1;
}
int IsFull() // returns 1 if Queue is full
{
return q.re == Size-1;
}
// Add new element at the rear end. Also called enqueue operation.

void Add( int v )


{
if( IsFull() )
printf("Queue is full..!\n");
else
{
if( IsEmpty() )
q.fe =0;
These notes are also available at :
www.santoshkabirsir.com

q.a[ ++q.re ] = v;
}
}

// Return and remove element from front of Q. Also called dequeue operation.

int Remove()
{
Prepared by, Santosh Kabir
Mobile: 98336 29398

4 of 12

3.Queues
www.santoshkabirsir.com

DS DSAA ( Common Topics )


int v;
v = q.a[ q.fe++ ];
if( q.fe > q.re ) //Q has become empty
q.fe = q.re = -1;
return v;
}
void Display()
{
int i;
if( IsEmpty() )
printf("Queue is Empty..!\n");
else
{
printf("Queue elements ... ");
for( i=q.fe; i<=q.re; i++)
printf("%d\t" , q.a[i]);
printf("\n");
}
}
int Front() // Read and return first element in Q
{
int v;
v = q.a[ q.fe ];
return v;
}
void main()
{
int v, opt;
clrscr();
// Initialize empty Queue

q.fe = q.re = -1;


printf("Queue Operations\n");
while( 1 )
{
printf("\nAdd(EnQueue......1\n");
printf("Remove(DeQueue...2\n");
printf("Display Q ......3\n");
printf("Q Front .........4\n");
printf("Exit ...........5\n");
printf("Enter option :");
scanf("%d", &opt );
switch( opt )
{
Prepared by, Santosh Kabir
Mobile: 98336 29398

5 of 12

3.Queues
www.santoshkabirsir.com

DS DSAA ( Common Topics )

case 1: printf("Enter a value to Add:");


scanf("%d", &v );
Add( v );
break;
case 2 : if( ! IsEmpty() )
{
v = Remove();
printf("Removed value=%d\n", v );
}
else
printf("Queue is empty..!\n");
break;
case 3 : Display();
break;
case 4: if( ! IsEmpty() )
{
v = Front();
printf("Front value :%d\n", v );
}
else
printf("Queue is empty..!\n");
break;
case 5 : return;

// stop main() i.e. end program

}
}
getch();
}

Priority Queue:
( More notes on Priority Queue for IT in separate set)
A queue in which elements are organized into groups according to priority and
processed such that the highest priority elements are output (or processed and
removed from queue) first.

Min Priority Queue :


Here, an element with minimum value is removed (processed ) first. For this we can
either insert element in proper place in the Queue and remove smallest element
which is at the front of the queue. Or while removing smallest element is searched
and removed from queue and queue elements are shifted.
( we will arrange element in the queue while inserting new element )
Prepared by, Santosh Kabir
Mobile: 98336 29398

6 of 12

3.Queues
www.santoshkabirsir.com

DS DSAA ( Common Topics )


Whenever an element is added to the queue the element are rearranged according to
priority. Thus an algorithm for the add() function for a Priority queue will be as
follows.
A-6
Algo: AddItem( Element )
1. If (queue is full)
a. Display error message and exit the function
2. Else
a. From rear of the queue to front of the queue repeat following
If an element is larger than element to add
Shift element one position ahead
Else
Stop
b. Copy the new element at the place of the last shifted element
c. Increment rear position by one.
3. If ends

Rest of the algorithms and program will be same as that for simple queue.
// Add new element in the Queue according to the priority of new element.

void Add( int v )


{
int i;
if( IsFull() )
printf("Queue is full..!\n");
else
{
if( IsEmpty() )
q.fe =0;
// loop to get proper position for new element
for( i= q.re; i>=q.fe; i-- )
{
if( q.a[i] > v )
{
q.a[i+1] = q.a[i];
}
else
break;
}
q.a[i+1] = v;
q.re++;
}
}

Prepared by, Santosh Kabir


Mobile: 98336 29398

7 of 12

3.Queues
www.santoshkabirsir.com

DS DSAA ( Common Topics )

Circular Queue:
This is the most popular queue because of its efficiency.
Movement of elements is not required. Circular queue uses an array as if its a
circular structure.
The front-end position and rear-end position is updated on every addition or removal
of element in a queue. Thus, the movement of elements in the list is not required.
If last element in the array is filled, new element will be added to beginning of array
(i.e. in 0th index).
Consider an array of size 5 is used to implement a circular queue. Thus, we have lower index 0 and higher index 4
or we can keep maximum 5 items in the queue at a time. After addition of four items (say A, B , C and D) the front
end is 0 and rear-end is at 3. See the figure 5.2 below,
0
1
2
3
4
A
B
C
D
Queue
queue
fig.2
Front
rear
Now, if an item is removed (i.e. A is removed from the front) then the front position changes to 1 (i.e. item B is at
the front).
In circular queue if a last array element is filled then the items are added at the beginning of the array. Thus, the
array is assumed to be bent and joined at the two ends to form a circular structure as follows,
4
0
3

2
1
Following table shows front and rear positions after additions and removal of items.
Assume, there are 3 items in the queue (B,C and D) with front position at 1 and rear at 3.
Operation

Front Rear

Result

A,B,C are present

Item E added

E added

Item removed

B removed

Item F added

F added

Item G added

G added

Item H added

Error: queue is full

Item removed

C removed

Prepared by, Santosh Kabir


Mobile: 98336 29398

8 of 12

3.Queues
www.santoshkabirsir.com

DS DSAA ( Common Topics )


Adding element to the Queue:
For adding a new element in a queue, a rear end position will be incremented. If rear
end goes out of array size then the new element is added at 0th location, if it is empty.
A-7
Algo: AddItem( element )
Input the element to add to queue
If queue is not full then
Increment the rear-end position
If rear-end goes beyond array limit then
Make it 0
Put the element at the rear-end position
Else
Show queue overflow error

Removing an element from the Queue:


A-8
Algo: RemoveItem
Return : element removed front end of a queue
Read element from front end of a queue
Increment front end to move to next element.
If front crosses rear position, then
Make queue empty ( by initializing front=rear= -1 )
If after incrementing front goes out of the array limit
Then make front point to first element in the array,( i.e. reset front to 0 )
Return the element read from front end

Displaying Queue elements:


A-9
Algo : DisplayQueue
Read front end index into index variable
While the variable has not crossed rear end index, do
i.

Display element at the index

ii.

Increment the index

iii. If the variable crosses array limit


Reset it to first index i.e. 0

Functions for implementing Circular Queue using array.


int IsEmpty() // returns 1 if Queue is empty
{
return q.fe == -1;
}
int IsFull() // returns 1 if Queue is full
{
if ( ( q.fe - q.re == 1) || (q.fe==0 && q.re==Size-1 ) )
return 1;
else
return 0;
}
// Add new element at the rear end. Also called enqueue operation.

Prepared by, Santosh Kabir


Mobile: 98336 29398

9 of 12

3.Queues
www.santoshkabirsir.com

DS DSAA ( Common Topics )


void Insert( int v )
{
if( IsFull() )
printf("Queue is full\n");
else
{
if( IsEmpty() )
q.fe =0;
q.re++;
if( q.re == Size )
q.re = 0;
q.a[q.re] = v;
}

// Return and remove element from front of Q. Also called dequeue operation.

int Remove()
{
int v;
v = q.a[ q.fe++ ];
if( q.fe - q.re == 1 ) //Q has become empty
q.fe = q.re = -1;
if( q.fe == Size )
q.fe = 0;
return v;
}
void Display()
{
int i;
if( IsEmpty() )
printf("Queue is empty");
else
{
printf("Queue elements ...\n ");
i= q.fe;
while( 1 )
{
printf("%d\t" , q.a[i] );
i++;
if( i - q.re == 1)
break;
if( i == Size )
i =0;
}
printf("\n");
}
}

Queue using Linked List :


Prepared by, Santosh Kabir
Mobile: 98336 29398

10 of 12

3.Queues
www.santoshkabirsir.com

DS DSAA ( Common Topics )


Here, we assume every node of a list as an element of a Queue. Thus, the queue is
maintained in a Linked list.
Linked list operations are restricted to work on FIFO principal.
Root of the List is treated as Front End of queue and Remove operation of Queue
removes root node of linked list.
Last node of the list is treated as Rear end of Queue and Insert operation adds new
node at the end of the list.
Display operation displays list nodes from root to last.

Functions for Linked list implementation of Queue :


struct ListNode
// structure for Node
{
int data;
struct ListNode *next;
};
// Global var. for list i.e. Queue

struct ListNode

*fe=NULL, *re=NULL;

// Functions

int IsEmpty()
{
return fe == NULL;
}
void Insert( int v )
{
struct ListNode *nw;
nw = (struct ListNode*) malloc( sizeof(struct ListNode) );
nw->data = v;
nw->next = NULL;
if( fe == NULL )
fe = nw;
else
re->next = nw;
re = nw;
}
These notes are also available at :
www.santoshkabirsir.com

void Display()
{
Prepared by, Santosh Kabir
Mobile: 98336 29398

11 of 12

3.Queues
www.santoshkabirsir.com

DS DSAA ( Common Topics )


struct ListNode *r;
if( IsEmpty() )
printf("Queue is empty\n");
else
{
r = fe;
printf("Queue values...\n");
while( r != NULL )
{
printf("%d\t", r->data);
r = r->next;
}
printf("\n");
}
}
int Remove( )
{
int v;
v = fe->data;
fe = fe->next;
return v;
}
int Front( )
{
int v;
v = fe->data;
return v;
}

Classes for Engg. students:


FE SPA

Sem II

SE DS (Comp) , DSAA ( IT ) Sem III


OOPM (Java) ( Comp, IT) Sem III
Web Programming. (IT ) Sem IV
(JSP, C#, ASP.Net, PHP etc)

* With practicals *
Classes conducted by Santosh Kabir sir.

Contact: 98336 29398


Andheri, Dadar, Thane
----0000----

Prepared by, Santosh Kabir


Mobile: 98336 29398

12 of 12

3.Queues
www.santoshkabirsir.com

Das könnte Ihnen auch gefallen