DS (U2)
DS (U2)
UNIT-II
Queues: Queue abstract data type - Array implementation – circular queue - linked list
implementation of queues – priority queues – double ended queues – multiple stacks and
queues - application.
QUEUE ADT
A queue is an ordered collection of items from which items may be deleted at one end
called the front, and into which items may be inserted at the other end called rear of the
queue.
Queue Model
The basic operations on a queue are enqueue, which inserts an element at the end
of the list (called the rear), and dequeue, which deletes (and returns) the element at the
start of the list (known as the front). Figure shows the abstract model of a queue.
Model of a queue
Example:
Front
A B C
Rear
In this example, A is at the front of the queue and C is at the rear. An element has been
deleted from the front of the queue. i.e.,
Front
B C
Rear
DATA STRUCTURES II IT
UNIT-II
IMPLEMENTATION:
The simplest way to represent a queue is using one-dimensional array and here we need
two more variables front and rear, to hold the position within the array of the first and last
elements of the queue.
UNIT-II
Keep track of the number of elements that are actually in the queue, q_size. All
this information is part of one structure, except for the queue routines themselves,
no routine should ever access these directly.
The operations should be clear. To enqueue an element x, increment q_size and
q_rear, then set QUEUE[q_rear] = x. To dequeue an element, set the return value
to QUEUE[q_front], decrement q_size, and then increment q_front.
OPERATIONS:
INSERT OPERATION:
Insert operation inserts an element onto the queue. Queue is a dynamic structure that is
constantly allowed to grow and shrink and thus changes its size. But now we represented
the queue by means of array. An attempt to push an element onto the queue, when the
array is full, causes an overflow. Insert operation involves:
1. Check whether the array is full before attempting to insert another
element. If so halt execution.
2. Increment the rear pointer.
3. Insert the element at the rear point of the queue.
Structure Definition
Class queue
{
Protected:
struct queue
{
int queue_size;
int front;
DATA STRUCTURES II IT
UNIT-II
int rear;
int *queuearray[ ];
};
UNIT-II
if(is_full())
error("FULL QUEUE");
else
{
Q size++;
Increment(Q_rear);
Q_array[Q_rear]=x;
}
}
UNIT-II
}
Function to return the first element from the queue
It checks whether the queue is empty. If it is not empty, it returns the element at
the front of the queue
int front(queue q)
{
if (!isempty(q))
return q->queuearray[q->front];
}
Function to return and remove the first element from the queue
It checks whether the queue is empty. If it is not empty, it returns the element and
then removes the element at the front of the queue.
int frontanddelete(queue q)
{
if (isempty(q)
error("EMPTY QUEUE");
else
return (q->queuearray[q->front++]);
}
Function to check whether the queue is full or not
This function isfull() checks whether the queue is full or not. It returns true if
queue is full. If q->rear=q->max-1, then the queue is full.
int is_full()
{
return Q_size = =Full_queue;
}
DATA STRUCTURES II IT
UNIT-II
APPLICATIONS OF QUEUES
Numerous applications of queue structure are known in computer science. One
major application of queue is in simulation.
Another important application of queue is observed in implementation of various
aspects of operating system.
Multiprogramming environment uses several queues to control various programs.
DATA STRUCTURES II IT
UNIT-II
And, of course, queues are very much useful to implement various algorithms.
For example, various scheduling algorithms are known to use varieties of queue
structures.
General applications
There are several algorithms that use queues to give efficient running times.
When jobs are submitted to a printer, they are arranged in order of arrival.
Thus, essentially, jobs sent to a line printer are placed on a queue We say
essentially a queue, because jobs can be killed. This amounts to a deletion from
the middle of the queue, which is a violation of the strict definition.
Virtually every real-life line is (supposed to be) a queue. For instance, lines at
ticket counters are queues, because service is first-come first-served.
Another example concerns computer networks. There are many network setups
of personal computers in which the disk is attached to one machine, known as the
file server. Users on other machines are given access to files on a first-come first-
served basis, so the data structure is a queue.
Calls to large companies are generally placed on a queue when all operators
are busy.
In large universities, where resources are limited, students must sign a
waiting list if all terminals are occupied. The student who has been at a terminal
the longest is forced off first, and the student who has been waiting the longest is
the next user to be allowed on.
A whole branch of mathematics, known as queueing theory, deals with
computing, probabilistically, how long users expect to wait on a line, how
long the line gets, and other such questions. The answer depends on how
frequently users arrive to the line and how long it takes to process a user once the
user is served. Both of these parameters are given as probability distribution
functions. In simple cases, an answer can be computed analytically.
DATA STRUCTURES II IT
UNIT-II
An example of an easy case would be a phone line with one operator. If the
operator is busy, callers are placed on a waiting line (up to some maximum limit).
This problem is important for businesses, because studies have shown that people
are quick to hang up the phone.
(a) Simulation
Simulation is a modeling of a real life problem, in other words, it is the model of a
real life Situation in the form of a computer program.
The main objective of the simulation program is to study the real life situation
under the control of various parameters which affect the real problem, and is a
research interest of system analysts or operation research scientists.
Based on the results of simulation, actual problem can be solved in an optimized
way.
Another advantage of simulation is to experiment the danger area. for example,
areas such as military operations are safer to simulate than to field test, which is
free from any risk as well as inexpensive.
Simulation is a classical area where queries can be applied. Before going to
discuss the simulated modeling, let us study few terms related to it.
Any process or situation that is to be simulated is called a system. A system is a
collection of interconnected objects which accepts aero or more inputs and
produces at least one output, Figure(a).
For example, a computer program is a system where instructions are
interconnected objects and inputs or initialization values are the inputs and results
during the execution is output.
Similarly, a ticket reservation counter is also a system. Note that a system can be
composed of one or more smaller system(s).
DATA STRUCTURES II IT
UNIT-II
UNIT-II
In case of time-driven simulation, systems change its states with the change of
time and in event-driven simulation, systems changes its state whenever a new
event arrives to the system or exits from the system.
Now let us consider a system, its model for simulation study and then application
of queues in it.
Consider a system as a ticket selling centre. There are two kinds of tickets
available, namely, T1 and T2, which customers are to purchase. Two counters C1
and C2 are there (Figure).
Also assume that time required to issue a ticket of T1 and T2 are t1 and t2
respectively. Two queues Q1 and Q2 are possible for the counters C1 and C2
respectively.
With this description of the system, two models are proposed:
Model 1
Any counter can issue both type of tickets.
A customer when arrives goes to the queue which has lesser number of
customers; if both are equally crowded, then to Q1, the queue of counter C1.
Model 2
Two counters are earmarked, say. C1 for selling T1 and C2 for selling T2 only.
A customer on arrival goes to either queue Q1 orQ2 depending on the ticket, that
is, Customer for T1 will be on Ql and that for T2 will be on Q2.
DATA STRUCTURES II IT
UNIT-II
With the these assumptions, the objective of the simulation model is to study the
performance of the system under various conditions.
UNIT-II
With these basic assumptions and definition, the proposed simulation model may
be termed as discrete deterministic time-driven simulation model.
UNIT-II
One way to implement complex scheduling is to classify the work load according
to its characteristics and t o maintain separate process queues.
So far the environment is concerned, we can maintain three queues, as depicted in
Figure.
UNIT-II
A process entering the system is put in queue Q1. A process in Q1 is given a time
quantum τ of I0 ms, say, it does not finish within this time, it is moved to the tail
of queue Q2.
If Q1 is empty, the process at the front of queue Q2 is given a time quantum τ of
20 ms, say.
If it does not complete within this time quantum. it is pre-empted and put into
queue Q3.
Processes in queue Q3 are serviced only when queues Q1 and Q2 are empty.
Thus, with this strategy, CPU first executes all processes in queue Q1.
Only when Q1 is empty it will execute all processes in queue Q2. Similarly,
processes in queue Q3 will only be executed if queues Q1 and Q2 are empty.
DATA STRUCTURES II IT
UNIT-II
UNIT-II
PRIORITY QUEUES
A queue in which we are able to insert items or remove items from any position based on
some property (such as priority of the task to be processed ) is often referred to as a
priority queue.
Fig : Represents a priority queue of jobs waiting to use a computer.
UNIT-II
Priorities of 1, 2, and 3 have been attached to jobs of type real-time, on-line , and batch,
respectively. Therefore, if a job is initiated with priority i, it is inserted immediately at the
end of the list of other jobs with priority i, for i=0,1,2 or 3. In this example, jobs are
always removed from the front of the queue. (In general, this is not a necessary restriction
on a priority queue.)
A priority queue can be conceptualized as a series of queue representing situations i
which it is known a priori what priorities are associated with queue items.
Priority 1:
R1 R2 ......................... Ri-1
…….
Priority 2:
Priority 3:
The above fig shows how single -priority queue can be visualized as three separate
queues, each exhibiting a strictly FIFO behavior .Elements in the second queue are
removed only when the first queue is empty , and from the third queue are removed only
when the first and second queues are empty. This separation of a single-priority queue
into a series of queues also suggests an efficient storage representation of a priority
queue. When elements are nserted, they are always added at the end of one of the queues
DATA STRUCTURES II IT
UNIT-II
A priority queue is another variation of queue structure. Here, each element has
been assigned a value, called priority of the element, and an element can be
inserted or deleted not only at the ends but at any position on the queue.
Priority queue is a data structure that is not a queue as per the definition: priority
queue does not strictly follow First-In First-Out (FIFO) principle which is the
basic principle of a queue.
Nevertheless, the name is now firmly associated with this particular data type.
However, there are various models of priority queue known in different
applications. Consider a particular model of priority queue.
UNIT-II
2. Two elements with the same priority are processed according to the order
in which they were added to the queue.
Here, process means two basic operations namely insertion or deletion. There are
various ways of implementing the structure of a priority queue. These are
b. Multi-queue implementation
The element can be inserted at the REAR end as usual. The deletion operation
will then be performed either of the two following ways.
a. Starting from the FRONT pointer, traverse the array for an element of the
highest priority. Delete this element from the queue. If this is not the front
most element shift all its trailing elements after the deleted element one stroke
each to fill up the vacant position. This implementation, however, is very
inefficient as it involved searching the queue for the highest priority element
and shifting the trailing elements after the deletion.
DATA STRUCTURES II IT
UNIT-II
b. Add the elements at the REAR end as earlier. Using a stable sorting
algorithm, sort the elements of the queue so that the highest priority elements
is at the FRONT end. When a deletion is required, delete it from the FRONT
end only.
The second implementation is comparatively better than the first one; here the
only burden is to sort the elements.
Multi-queue implementation
This implementation assumes N different priority values. For each priority Pi
there are two pointers Fi and Ri corresponding to FRONT and REAR pointer
respectively. The elements between Fi and Ri are all of equal priority value Pi, fig
represents a view of such structure.
With this representation, an element with priority value P i, will consult Fi for
deletion and Ri for insertion. But this implementation is associated with number
of difficulties.
DATA STRUCTURES II IT
UNIT-II
2. Large number of pointers are involved when the range of priority values
are large.
It is clear from fig (a) that for each priority value a simple value a simple queue
is to be maintained. An element will be added into a particular queue
depending on its priority value.
The priority as shown in fig(b) is some way better than the multi-queue with
multiple queues. Here one can get rid off maintaining several pointers for
FRONT and REAR in several queues. Multiqueue with multiple queues has
one advantage that one can have different queues of arbitrary length. in some
application, it is seen that, number of occurrence of elements with some
priority value is much larger than other value, thus demanding a queue of
larger size.
DATA STRUCTURES II IT
UNIT-II
insert( )
{
struct node *tmp,*q, *p;
int added_ item, item_ priority;
tmp = (struct node *)malloc(sizeof(struct node));
DATA STRUCTURES II IT
UNIT-II
if(tmp== NULL)
fatal error (“out of space”);
else
{
tmp->info = added_item;
tmp->priority = item_priority;
}
if( q->next == NULL || item_priority < q->next ->priority )
{
tmp->next = q->next;
q->next = tmp;
}
else
{
p = q;
while( p->next != NULL && p->next->priority <= item_priority )
p=p->next;
tmp->next = p->next;
p->next = tmp;
}
}
del( )
{
struct node *tmp;
if(q->next == NULL)
display „Queue Underflow‟
else
{
tmp = q->next;
q->next = tmp ->next;
DATA STRUCTURES II IT
UNIT-II
free(tmp);
}
}
IMPLEMENTATION OF DEQUEUE
The Deque is a short form of DOUBLE ENDED QUEUE and defines a data structure in
which items can be added or deleted at either the front or rear and , but no changes can be
a made elsewhere in the list. Thus a Deque is a generalization of both a stack and a
queue.
Insertion
12 53 61
24 19
Insertion
Deletion
Insertion
Front Top
Inserting Element:
Steps to be Followed:-
1. Check whether the Deque is full or not .
2. Check whether the element is the first to be added.
a. If it is true then set the values of front and rear to zero.
3. Insert the given element.
Position : Beginning of Deque
Steps to be Followed:-
DATA STRUCTURES II IT
UNIT-II
UNIT-II
Deletion
12 53 61 Deletion
24 19
Insertion
Front Top
Deletion
Insertion 12 53 61
24 19
Insertion
Insertion
Front Top
Fig shows the representation of output – Restricted Deque
DATA STRUCTURES II IT
UNIT-II
Allocate the memory location using malloc function and if the queue is empty
then the front and the rear element are the same
For deletion operation check if the queue has only one element if so perform
deletion. if the queue contains more elements then perform deletion accordingly.
For the display operation use the while loop and check if x->link!=NULL if so
print the elements.
For the display operation if rear== null then print that the queue is empty
Program:
struct node
{
int data;
struct node *next;
};
struct node *front=NULL,*rear=NULL,*x;
void enqfro(element_type x )
{
ptr tonode tempcell;
if(front = = NULL)
{
tempcell =(struct node*)malloc(sizeof(struct node));
tempcell ->data = x;
tempcell ->next = NULL;
DATA STRUCTURES II IT
UNIT-II
void deqrea()
{
if(rear==NULL)
display(Queue is empty);
else
{
x=rear;
display (x->data);
rear=x->link;
free(x);
}
}
void enqrea()
{
if(rear==NULL)
{
DATA STRUCTURES II IT
UNIT-II
void deqfro( )
{
if(front==NULL)
display(Queue is empty);
else
{
x=front;
display (deleted element is ,x->data);
front=x->link;
free(x);
}
}
DATA STRUCTURES II IT
UNIT-II
void display2( )
{
if(front==NULL)
display("queue is empty");
else
{
x=front;
while(x->link!=NULL)
{
display(x->data);
x=x->link;
}
display(x->data);
}
}
void display1( )
{
if(rear==NULL)
display(queue is empty);
else
{
x=rear;
while(x->link!=NULL)
{
display(x->data);
x=x->link;
DATA STRUCTURES II IT
UNIT-II
}
display (x->data);
}
}
Let us see about the data representation needed for several stacks and queues. Here also
we are going to use array v(1:m) for sequential mapping.
Consider, we are having two stacks to represent here we can use v(1) for the bottom most
element in stack one and v(m) for the corresponding element in stack 2. Stack 1 can
grow towards v(m) and stack 2 towards v(1). So that available space can be efficiently
utilized.
We cannot do the same procedure for representing more than two stacks. Because in a
one dimensional array we are having only two fixed points v(1) and v(m) to represent
bottom most element.
In this case, when more than two stacks ,say n, are to be represented sequentially, we can
initially divide out the available memory v(1:m) into n segments and allocate one of these
segments to each of the n stacks. Thus division of v(1:m) into segments may be done in
proportion to expected sizes of the various stacks if the sizes are known.
DATA STRUCTURES II IT
UNIT-II
In the absence of such information, (1:m) may be divided into equal segments. For each
stacks i we shall use B(i) to represent a position one less than the position in v for the
bottom most element of that stack. T(i),1 < i < n will point to the topmost element of the
stack i. Here ,we are going to use the boundary condition B(i)=T(i), If the ith stack is
empty.
If we grow the ith stack in lower memory indexes then the i+1 st
then with equal initial segments we have the initial values of B(i) and T(i) as
B(i)=T(i)=m/n(i-1),1< i < n
UNIT-II
The above algorithm will be suitable for only 1 or 2 stacks since STACK-FULL
condition in algorithm ADD does not imply that all m location of V are in use. In fact,
there may be a lot of unused space between stacks j and j+1 for 1 <= j <= n and j = i
which is shown in the following fig:
…. ….
B(1) T(1) B(2) T(2) B(i) T(i) T(i+1) T(j) B(j+1) B(n+1)
B(I+1)B(I+2)
Fig: Configuration when stack i meets with stack i+1 but there is still free space else
where in v.
The procedure STACK_FULL(i) should therefore determine whether there is any free
th
space around so as to make some of these free space available to the i stack, the
primary objective of the algorithm STACK FULL is to permit the adding of elements to
stack so long as there is some free space in v and shift stack around so as to make some
DATA STRUCTURES II IT
UNIT-II
of these free space available to the Jth stack. The primary objective of algorithm STACK
FULL is to permit the adding of elements to stack so long as there is some free space in
v.
PROCEDURE:
a) Determine the least j ,i <j<n such that there is free space between stacks j and j+1,
that is T(j)<B(j+1). If there is such a j, then move stacks i+1,i+2,…j one position to
the right, thereby creating a space between stacks i and i+1.
b) If there is no j as in (a), then look to the left of stack i. Find the largest j such that
1<=j<i and there is space between stacks j and j+1 that is, T(j) <B(j+1). If there is
such a j, then move stack j+1, j+2,…,i once space left creating free space between
stacks i and i+1.If there is no j satisfying either the conditions of (a)or(b),then all in
spaces of v are utilized and there is no free space.
LINKED QUEUE:
In queue,items are deleted from the front of a queue and inserted at the rear. Let a
pointer to the first element of the list represent the front of the queue .Another pointer
to the last element of the list represents the rear of the queue as shown in the
following figure: ALGORITHM:REFER CLASS NOTES
DATA STRUCTURES II IT
UNIT-II
APPLICATIONS OF A LIST
In order to store and process data, linked list are very popular data structures.
This type of data structures hold certain advantages over arrays.
UNIT-II
Next, linked lists consume extra space than the space for actual data as the links
among the nodes are to be maintained.
UNIT-II
{
int coeff_array[ MAX_DEGREE+1 ];
unsigned int high_power;
} *POLYNOMIAL;
Type declarations for array implementation of the polynomial ADT
An alternative is to use a singly linked list. Each term in the polynomial is
contained in one cell, and the cells are sorted in decreasing order of exponents.
For instance, the linked lists in represent p1(x) and p2(x).
POLYNOMIAL ADDITION:
A(x)=
Where ai are non-zero coefficients with exponent ei such that em>em-1>..>e2>e1>0.
Each term will be represented by a node.A node will be of fixed size leaving 3 fields
which represent the coefficient and exponent of a term plus a pointer to a next term.
COEF EXP
LINK
UNIT-II
In order to add two polynomial together we examine their terms starting at the nodes
pointed to be A and B.Two pointer p and q are used to move along the terms of A and B.
If the exponent of the two terms are equal then the coefficient terms are added and the
new term created for the result.
If the exponent of the current term is less then exponent of the current term of B then a
duplicate of the term of B is created and attached to C .The pointer q is advanced to the
next term.
Similar action is taken on A if EXP(p)EXP(q).If one polynomial gets exhausted we must
exit and the remaining terms of the other can be copied directly into result.
The following figure illustrate this addition procedure on the polynomial A and B given
above.
DATA STRUCTURES II IT
UNIT-II
Each time a new node is generated into COEF and EXP fields are set and it is appended
to the end of the list C.In order to avoid having to search for the last node in C each time
a new node is added ,we keep a pointer d which points to the current last node in C.
Procedure PADD specifies the algorithm to add two polynomial .PADD makes use of a
subroutine ATTACH which creates a new node and appends it to the end of C.In order to
avoid more computation,C is initially given a single node with no values which is
deleted at the end of the algorithm.
Procedure ATTACH(C,E,d)
//create a new term with COEF=c and EXP=E and attach it to the node pointed at by d//
Call GETNODE(I)
DATA STRUCTURES II IT
UNIT-II
EXP(I) E
COEF( I)C
LINK (d) //attach this node to the end of this list//
DI //move pointer d to the new last node end ATTACHED
Procedure AADD(A,B,C)
//polynomial A and B represented as singly linked list are summed to form the new list
named C//
1. PA ;qB//p,q pointer to next term of A ,B//
2. call GETNODE (C)dc //initial node for c,returned latar//
3.While p!=0 and q!=0//While there are more term in A ,B
4.Case
5.:EXP(p)=EXP(q)://equal exponent//
6.xCOEF(p)+COEF(q)
7.if x!=0 then call ATTACH (x,EXP(p),d)
8.pLINK(p);qLINK (q)// advance to next term//
9.else:call ATTACH (COEF(p),EXP(p),d)
10.pLINK (p)//advance to the next term of A//
11.end
12. end
13. While p!=0 do //copy remaining term of A//
14.Call ATTACH (COEF(p),EXP(p),d)
15. PLINK(p)
16. end
17. while q!=0 do //copy remaining list of B//
18.call ATTACH (COEF(q),EXP(q),d)
19. q LINK(q)
20. end
21. LINK (d)0.tc;cLINK( c)
22.Call RET(t) //delete extra initial node //
DATA STRUCTURES II IT
UNIT-II
COMPUTING TIME:
In order to carry out a computing time analysis, it is first necessary to determine which operation contribute to the cost for this
algorithm. There are several cost measures.
UNIT-II
SPARSE MATRIX:
We’ve already seen one of the method of storing sparse arrays,i.e ,by using a 3-tuple for
each element.
As matrix operation such as addition, subtraction and multiplication are performed ,the
number of non-zero terms in the matrix need to added or deleted .That requires a lot of
data movement in the static storage system.
An important over this would be to store these non-zero element as a linked list of 3
tuples instead of using an array.
In the Data representation ,each column of a sparse matrix will be represented by a
circular by linked list with head node.In addition ,each row will also be a circularly
linked list with a head node .Each node in the l structure other than a head node will
represent a non-zero term in the matrix A will be made up of 5 fields:
ROW,COL.DOWN,RIGHT and VALUE.
Here, the Down field will be used to link to the next non-zero element in the same
column,while the RIGHT field will be used to link to the next non-zero element in the
same row.
Thus,if aij!=0,then there will be a node with VALUE field aij,ROW field I and COL field
j,this node will be linked into the circular linked list for row I and also into the circular
linked list for column j.Ait will therefore,be a member of two list at the same time.
In order to avoid having nodes of two different sizes in the system ,we shall assume head
node to be configured exactly as a nodes being used to represent the non-zero terms of
the sparse matrix. The row and COL field of head nodes will be set to zero by assuming
the indices value >0.
FIG2: Shows the structure obtained for the 6*7 matrix a fig 1:
0 0 11 0 0 13 0
12 0 0 0 0 0 14
DATA STRUCTURES II IT
UNIT-II
0 –4 0 0 0 –8 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 –9 0 0 0 0 0
FIG1: 6*7 sparse Matrix A
The head nodes are marked M1-M7.As can be seen from the figure ,the VALUE field of
the head nodes for each column list is used to link to the next head node.while the
DOWN field links to the first non-zero term in that column or to itself if there Is no non-
zero term in that column.This leaves the RIGHT field in unutilised .The head node is the
RIGHT field utilised by the row head nodes ,hence it is possible to use the same node as
the head node foe row i as for column i.
The head nodes themselves,linked through the VALUE field ,from a circular linked list
with a head node pointed to by A .This head node for the list of row and column head
nodes contain the dimensions of the matrix.
i.e Row (A) is the number of rows in the matrix and COL(A) is the number of column.
If we wish to represent a n*m sparse matrix with r non-zero term then the number of
nodes needed is r+max{n,m}+1.
UNIT-II
UNIT-II
r- no.of non-zero terms are given as input by r triple of the form (I,j,aij).The triple are
ordered by the rows and within each row,the triple are ordered by columns.
hdnode is an array with max size of largest dimension of a given matrix in which hdnode
will be a pointer to the head for column i,and hence also for row i. Algorithm mread
proceed by first setting up all the head nodes and the settiing up each row list,
Simultaneously building the coulmn list .The VALUE field of head node I is initially
used to keep track of the last node in column i