You are on page 1of 21

Data structures Lecture Notes Unit - II

2.2 Queues
 A Queue is a linear list in which data can only be inserted at one end, called the rear, and deleted
from the other end, called the front.
 These restrictions ensure that the data are processed through the queue in the order in which
they are received.
 In the other words, a queue is a first in first out (FIFO) structure.
 A queue is same as a line
Ex:
a. A line of people waiting for the bus at a bus station is a queue,
b. A list of calls put on held to be answered by a telephone operator is a queue and
c. A list of waiting jobs to be processed be a computer is a queue
 Fig shows two representations of a queue
a. Queue of a people and
b. Computer queue

 Both people and data enter the queue at the rear and progress through the queue until they
arrive at the front
 Once they are at the front of the queue, they leave the queue and are served.
2.2.1 Basic Operations:
 Four basic operations:
o Data can be inserted at the rear
o Deleted from the front
o Retrieved from the rear
o Retrieved from the front
 Difference of stack and queue is implementation needs to keep track of the front and the rear of
the queue; whereas stack only worry about one end the top.
 Definition: A queue is a list in which data can be inserted at one end, called the rear and deleted
from the other end, called the front. It is a first in first out (FIFO) restricted data structure.
a. Enqueue
 The queue is insertion operation is known as enqueue

1
Data structures Lecture Notes Unit - II

 After the data have been inserted into the queue, the new element becomes rear.
 The only potential problem with enqueue is running out of room for the data
 If there is not enough room for another element in the queue, the queue is an overflow state.
Enqueue inserts an element at the rear of the queue
Figure shows the enqueue operation

b. Dequeue
 The queue delete operation is known as dequeue
 The data at the front of the queue are returned to the user and removed from the queue
 If there are no data in the queue when a dequeue is attempted, the queue is in an underflow state
Dequeue deletes an element at the front of the queue
The dequeue operation is shown in fig.

c. Queue front:

2
Data structures Lecture Notes Unit - II

 Data at the front of the queue can be retrieved with queue front
 It returns the data at the front of the queue without changing the contents of the queue
 If there are no data in the queue when a queue front is attempted, then the queue is in underflow
state.
Queue front retrieves the element at the front of the queue
 The queue front operation is as shown in figure

d. Queue Rear
 The queue rear retrieves the data at the rear for the queue
 It is known as queue rear
 As with queue front, if there are no data in the queue when a queue rear is attempted, the queue
is an underflow state
Queue rear retrieves the element at the rear of the queue
 The queue rear operation is shown in figure

Queue example

3
Data structures Lecture Notes Unit - II

2.2.2. Array representation of Queues:


A queue is linear, sequential list of items that are accessed in the order First in First Out(FIFO).
The first item inserted in a queue is also the first one to be accessed. This is accomplished by
inserting at one end (the rear) and deleting from the other (the front).

front = 0

To insert: put new element in location 4, and set rear to 4

To delete: take element from location 0, and set front to 1

4
Data structures Lecture Notes Unit - II

rear = 3
front = 0

Initial queue:
17 23 97 44

Notice how the array contents “crawl” to the right as elements are inserted and deleted

This will be a problem after a while!

Array implementation of queues for Enqueue:


int rear=front=-1;
enqueue(int ele)
{
if(rear==MAX-1)
printf(“queue overflow\n”);
else
{
if(front==-1)
front=0;
rear=rear+1;
queue[rear]=ele;
}
}
Array implementation of queues for dequeue:
dequeue()
{
if(front==-1||front>rear)
printf(“queue underflow\n”);
else
{

5
Data structures Lecture Notes Unit - II

printf(“element deleted from queue: %d”,queue[front]);


front=front+1;
}
}
Array implementation of queues for display:
display()
{
if(front==-1||front>rear)
printf(“queue is empty\n”);
else
{
for(i=front;i<=rear;i++)
printf(“%d”,queue[i]);
}
}
2.2.3. Circular Queue:
 In linear queues once the element is deleted from queue, that location cannot be filled.
 So the drawback of linear queue is wastage of memory. This problem can be solved by circular
queues
 Circular queue is a linear list in which once the rear pointer reaches maxsize-1 then it is reset to 0.
i.e. making the queue as circular. Similarly, when the front pointer reaches maxsize-1 then it is reset
to 0.
Implementation of circular queue can be done in two methods:
1. The front = rear = -1
2. To use MOD (%) operator. In this the front = 0 and rear = -1
Basic operations of the circular queue:
 Enqueue
 Dequeue
 Display
Implementation of a circular queue:

6
Data structures Lecture Notes Unit - II

7
Data structures Lecture Notes Unit - II

Enqueue:
1. Check for the overflow condition. Overflow occurs in circular queue when front = 0 and rear =
max-1 or front = rear + 1
2. Increment rear pointer by one and insert element into the location where rear is pointing
3. If rear pointer reached max – 1 and there are empty locations in the circular queue then set the
rear pointer to 0. i.e. its points to the starting location.

Dequeue:
1. Check for underflow condition. Underflow occurs when front = -1 and rear = -1
2. Take out the element into the temporary variable
3. If front = rear then set front = -1 and rear = -1
4. Otherwise if front reaches max-1 then set front pointer to 0.(i.e. starting location)
5. Otherwise Increment front pointer by one

Working of a circular Queue


Assume the circular of 4 elements.

Implementation of Circular Queue using Arrays


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define MAX 5
int q[MAX], ele, r=-1, f=-1, ch;
void enqueue();
void dequeue();
void display();
void main()
{
clrscr();
printf("1. Enqueue\n2. Dequeue\n 3. Display\n 4. Exit\n ");
do
{
printf("\nenter the choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: enqueue();
break;
case 2: dequeue();
break;
case 3:display();

8
Data structures Lecture Notes Unit - II

break;
case 4: exit(0);
}
}while(ch!=4);
}
void enqueue()
{
if((f==0)&&(r==MAX-1)||(f==r+1))
{
printf("overflow\n");
}
else
{
printf("enter the element\n");
scanf("%d",&ele);
if(f==-1)
{
f=0;
r=0;
}
else if(r==MAX-1)
r=0;
else
r=r+1;
q[r]=ele;
}
}
void display()
{
int i;
printf("the elements in circular queue are\n");
if(f>r)
{
for(i=f;i<=MAX-1;i++)
{
printf("%d\t",q[i]);
}
for(i=0;i<=r;i++)
{
printf("%d\t",q[i]);
}
}

9
Data structures Lecture Notes Unit - II

else
{
for(i=f;i<=r;i++)
{
printf("%d\t",q[i]);
}
}
}
void dequeue()
{
if(f==-1)
{
printf("underflow\n");
}
else
{
ele=q[f];
if(f==r)
{
f=-1;
r=-1;
}
else if(f==MAX-1)
f=0;
else
f++;
printf("the deleted element is %d",ele);
}
}
Output

10
Data structures Lecture Notes Unit - II

2.2.4. Priority Queue:


 A Special form of queue from which items are removed according to their designated priority
and not the order in which they entered.

Jo b # 4 Jo b # 1
S u p e r v is o r M an ager

Jo b # 2 Jo b # 3
P r e s id e n t C le r k

 Items entered the queue in sequential order but will be removed in the order #2, #1, #4, #3.
 A Priority Queue is a container in which access or deletion is of the highest-priority item,
according to some way of assigning priorities to items.
C Implementation for priority queue:
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
void insert_by_priority(int);
void delete_by_priority(int);
void create();
void check(int);
void display_pqueue();
int pri_que[MAX], front, rear;

11
Data structures Lecture Notes Unit - II

void main()
{
int n, ch;
printf("\n1 - Insert an element into queue");
printf("\n2 - Delete an element from queue");
printf("\n3 - Display queue elements");
printf("\n4 - Exit");
create();
while (1)
{
printf("\nEnter your choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("\nEnter value to be inserted : ");
scanf("%d",&n);
insert_by_priority(n);
break;
case 2:
printf("\nEnter value to delete : ");
scanf("%d",&n);
delete_by_priority(n);
break;
case 3:
display_pqueue();
break;
case 4:
exit(0);
default:
printf("\nChoice is incorrect, Enter a correct choice");
}
}
}
/* Function to create an empty priority queue */
void create()
{
front = rear = -1;
}
/* Function to insert value into priority queue */
void insert_by_priority(int data)
{

12
Data structures Lecture Notes Unit - II

if (rear >= MAX - 1)


{
printf("\nQueue overflow no more elements can be inserted");
return;
}
if ((front == -1) && (rear == -1))
{
front++;
rear++;
pri_que[rear] = data;
return;
}
else
check(data);
rear++;
}
/* Function to check priority and place element */
void check(int data)
{
int i,j;
for (i = 0; i <= rear; i++)
{
if (data >= pri_que[i])
{
for (j = rear + 1; j > i; j--)
{
pri_que[j] = pri_que[j - 1];
}
pri_que[i] = data;
return;
}
}
pri_que[i] = data;
}
/* Function to delete an element from queue */
void delete_by_priority(int data)
{
int i;
if ((front==-1) && (rear==-1))
{
printf("\nQueue is empty no elements to delete");
return;

13
Data structures Lecture Notes Unit - II

}
for (i = 0; i <= rear; i++)
{
if (data == pri_que[i])
{
for (; i < rear; i++)
{
pri_que[i] = pri_que[i + 1];
}
pri_que[i] = -99;
rear--;
if (rear == -1)
front = -1;
return;
}
}
printf("\n%d not found in queue to delete", data);
}
/* Function to display queue elements */
void display_pqueue()
{
if ((front == -1) && (rear == -1))
{
printf("\nQueue is empty");
return;
}
for (; front <= rear; front++)
{
printf(" %d ", pri_que[front]);
}
front = 0;
}
Output:

14
Data structures Lecture Notes Unit - II

2.2.5. Deque:
Definition:
 A deque is a linear list in which elements can be added or removed at either end but not in the
middle. The term deque is double ended queue.
(or)
 A double ended queue is a linear list in which insertions and deletions are done from both ends but
not in the middle.
The following is the typical structure of a deque:

 In linear queue, elements are inserted from rear and deleted from front. But, in deque elements can
be inserted from front and elements can be deleted from rear.
The following operations can be performed on deque.
 Front insertion

15
Data structures Lecture Notes Unit - II

 Front deletion
 Rear insertion
 Rear deletion
 The operations front deletion and rear insertion are same as in linear queue.
Rear deletion:
 If deque is empty then rear deletion is not possible
 To perform rear deletion, first take out the element from the location, which is pointed by rear
and decrement rear by 1

Front insert:
 If the deque is full then front insertion is not possible. If the first location of queue is empty then
front insertion is possible.
 To insert element from front, first decrement front by 1 and place the element into the location
where front is pointing.
Insert 50 into the deque from front end.

C Implementation of Deque using arrays


#include<stdio.h>
#include<conio.h>
#define max 4
int q[max],ele,f=0,r=-1,ch;
void rdequeue()
{
if((f==0)&&(r==-1))
printf("underflow\n");
else
if(r==f)
{
printf("%d",q[r]);

16
Data structures Lecture Notes Unit - II

r=-1;
f=0;
}
else
printf("%d",q[r--]);
}
void fdequeue()
{
if((f==0)&&(r==-1))
printf("underflow\n");
else
if(f==r)
{
printf("%d",q[f]);
f=0;
r=-1;
}
else
printf("%d",q[f++]);
}
void renqueue(int ele)
{
if(r==max-1)
printf("overflow\n");
else
q[++r]=ele;
}
void fenqueue(int ele)
{
if((f==0)&&(r==-1))
q[++r]=ele;
else
if(f!=0)
q[--f]=ele;
else
printf("front insertion is not possible");
}
void display()
{
int i;
if(f==0&&r==-1)
printf("list empty");

17
Data structures Lecture Notes Unit - II

else
{
for(i=f;i<=r;i++)
printf("%d",q[i]);
}
}
void main()
{
clrscr();
printf("\n1.rearenqueue\n2.frontenqueue\n3.frontdequeue\n4.reardequeue\n5.display\n6.exit\n");
do
{
printf("\nenter choice");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("enter the ele");
scanf("%d",&ele);
renqueue(ele);
break;
case 2:printf("enter the ele");
scanf("%d",&ele);
fenqueue(ele);
break;
case 3:fdequeue();
break;
case 4:rdequeue();
break;
case 5:display();
break;
case 6:exit(0);
}
}while(ch!=6);
}
Output:

18
Data structures Lecture Notes Unit - II

2.2.6. Applications of Queues:


 Queue are one of the more common data processing structures
 These are virtually found in every operating system and every network and in countless other areas
 For ex, queue can be used in business online applications such as processing customer requests, jobs
and orders
 In this section we discuss the queue implementation Categorizing data
Categorizing Data:
 Sometimes we need to rearrange data without destroying the basic sequence.
 An ex, consider list of numbers
 We need to group the numbers while maintaining their original order in each grop
 It is an excellent multiple queue application.
 Consider the following list of numbers:
3 22 12 6 10 34 65 29 9 30 81 4 5 19 20 57 44 99
 We want to categorize them into four different groups:
Group 1: less than 10
Group2: between 10 and 19
Group3: between 20 and 29
Group4: 30 and greater
 In other words, we want the list rearranged as shown below
|3 6 9 4 5|12 10 19| 22 29 20| 34 65 30 81 57 44 99|

19
Data structures Lecture Notes Unit - II

 This is not sorting. The result is not a sorted list but rather a list categorized according to the
specified rules
 The numbers in each group have kept their original order.
 Categorizing data design:
 The solution is simple
 We build a queue for each of the four categories.
 We then store the numbers appropriate queue as we read them
 After all the data has been processed we print each queue to demonstrate that we categorized the
data correctly.
 The design of algorithm is as shown
Category Queues
Algorithm categorize
Group a list of numbers into four groups using four queues.
1 createQueue (q0to9)
2 createQueue (q10to19)
3 createQueue (q20t029)
4 createQueue (qOver29)
5 fillQueues (q0to9, q10t019, q20to29, qOver29)
6 printQueues (q0to9, q10t019, q20to29, qOver29)
end categorize
 The pseudocode to fill the queue is shown in algorithm
Fill category Queues
Algorithm fillQueues (q0to9, q10to19, q20to29, qOver29)
This algorithm reads data from the keyboard and places them in one of four queues.
Pre all four queues have been created
Post queues filled with data
1 loop (not end of data)
1 read (number)
2 if (number < 10)
1 enqueue (q0to9, number)
3 else if (number <20)
1 enqueue (q10to19, number)
4 else if (number < 30)
1 enqueue (q20to29, number)
5 else
1 enqueue (qOver29, number)
6 end if
2 end loop
end fillQueues

20
Data structures Lecture Notes Unit - II

2.3. Dynamic Memory Allocation:


 In static memory allocation, memory is allocated to the variables and arrays at compile time
 Allocating memory to the objects at run time is called dynamic memory allocation
 To access the dynamic data pointers are used.
Memory management functions
Four types of functions are:
 malloc()
 calloc()
 realloc()
 free()
first three functions are used to allocate memory and the last one is used to free the
memory that is not in use. All this are available in the standard library function.
Malloc:
 Malloc function is used to allocate a block of memory and it returns void pointer to the address of
first byte in the memory
 Ex: x=(int*)malloc(sizeof(int));
Calloc:
 It allocates memory dynamically for arrays. The only difference between calloc and malloc is that
calloc sets memory to null character but malloc doesn’t.
 Ex: int c[]=(int *)calloc(50,sizeof(int));
Here, an array of 50 integers is allocated.
Realloc:
 Realloc resizes the block of memory either by deleting or extending the memory block
 It allocates new block, if the existing block cannot be extend and copies the existing memory
allocation the new block and deletes the old one
Free:
 Free function is used to free the memory allocation allocated by malloc, calloc and realloc when
they are no longer in use and the memory block can be reused later.
 Ex: free(ptr);

21

You might also like