DATA
STRUCTURES
WEEK 4
[email protected]
Outline
z Definition and ADT
z Applications
z Implementation
Linear
Circular
z Priority Queue
z Double Ended Queue
3
Queue
z Logical Model: A queue is a collection
of homogeneous items (elements), in
which new elements are added from
one end (the rear), and elements are
removed from the other end (the front).
z A queue is a FIFO “first in, first out”
structure.
4
Stack vs. Queue
5
The Queue ADT
A Queue is a collection of items of type T on
which following operations are defined:
z Initialize the queue to be the empty queue.
z Determine whether or not the queue is empty.
z Determine whether or not the queue is full.
z If Queue is not full, insert a new item from the
rear of the queue.
z If Queue is not empty, remove an item from
the front of the queue.
6
Applications of Queues
z Many systems in everyday life incorporate
queues:
At the supermarket checkout counters
At banks, airports
At petrol/gas stations etc.
z Each of these systems shares common feature:
There are servers who dispense the service.
There are queues of clients waiting in a first-
come first-served order for service.
7
Applications of Queues
z Queues are very common in
Networking
– routers queue packets before sending them out
Operating systems
– CPU scheduling, resource management etc.
System modeling and simulation
Queuing Theory
8
Queues in Operating Systems
z Many operating systems use queues of tasks
to regulate the work performed by a computer.
z In this case, task records (representing
user's jobs) are placed in queues to await
service by various components of system,
such as the printer, the CPU and storage
devices. All of these are shared resources.
9
Queues in Simulation and Modeling
z Queues are useful in setting up simulations and models
of the systems in which clients arrive and are given
service.
z In such systems, we try to model accurately the service
times taken by clients and we try to measure how well
the overall system performs.
z For example, we may be interested in measuring:
The average waiting time
The length of the queue
The throughput of the system (i.e., number of clients
served per hour).
10
Air Traffic Control System
11
Implementation of Queues
There are two basic approaches:
Æ A linear array
Æ A circular array
12
Queue Implementation
front rear
X A M
Insert(F)
front rear front rear
X A M F A M F
item = Remove()
13
Linear Array
z In a standard linear array
0 is the first element
arraylength – 1 is the last element
z All objects removed would come from
element 0
z All objects added would go one past the
last currently occupied slot
z To implement this, when an object is
removed, all elements must be shifted
down by one spot
14
Linear Array
front rear
A B F S D K M
Remove()
front rear
B F S D K M
shift
front rear
B F S D K M
15
Linear Array Drawback
z Very expensive structure to use for a
queue
z Would prefer to let the data “wrap-around”
the front would not always be zero
– it would be the first occupied cell
the last item may actually appear in the array
before the first item
this is called a circular array
16
Linear and Circular Array
0 1 3 4 6 7 8 9
2 5
A B C D E F G
rear
front
9 0 front
Circular view of arrays.8 1
A
B
rear
C 2
7
G D
F E 3
6
5 4
17
Circular Array
The “wrap-around” is accomplished
through the use of the mod operator (%)
rear = (rear + 1) % maxQue;
front = (front + 1) % maxQue;
18
Circular Array
front rear front rear
A B F S D K M S D K M A
Remove()
front rear Insert(F) front rear
B F S D K M F S D K M A
front = (front + 1) % 8 rear = (rear + 1) % 8
front rear rear front
B F S D K M F S D K M A
19
Queue Special Conditions
z Underflow
• if both front and rear are -1
z Overflow
ifthe rear of the list is one spot “behind” the
front of the list
front == (rear+1)%maxQue
20
Queue Special Conditions
z If front and rear are the same and not equal to -
1, there is only one item in the Queue
z Deletion of last element
modify both front and rear to -1
z Insertion of first element
modify both front and rear to 0
21
Insertion in a Queue: Qinsert (Q, N, Front, Rear, Item)
// Is Queue Full?
If (Front == 1 AND Rear == N) OR (Front == Rear + 1) Then
Write: OverFlow; Return;
// Find New Value of Rear
If (Front == Null) Then //Queue initially empty
Front = 1 and Rear = 1;
Else If (Rear == N) Then
Rear = 1;
Else
Rear = Rear + 1;
// Insert the element
Q[Rear] = Item;
Return;
22
Removal from a Queue: Qremove (Q, N, Front, Rear, Item)
// Is Queue Empty?
If (Front == Null) Then
Write: UnderFlow; Return;
// Remove Front element
Item = Q[Front];
// Find New Value of Front
If (Front == Rear) Then //Queue has one element
Front = Null and Rear = Null;
Else If (Front == N) Then
Front = 1;
Else
Front = Front + 1;
Return; 23
Queue ADT Operations
z Initialize -- Sets queue to an empty state.
z IsEmpty -- Determines whether the queue is currently
empty.
z IsFull -- Determines whether the queue is currently
full.
z Insert (ItemType newItem) -- Adds newItem to the rear
of the queue.
z Remove (ItemType& item) -- Removes the item at the
front of the queue and returns it in item.
24
Queue ADT Operations
Transformers
Initialize change state
Insert
Remove
Observers
IsEmpty observe state
IsFull
25
Queue Implementation
class Que
Que Private Data:
~Que front 2
rear 4
Insert
maxQue 5
‘C’ ‘X’ ‘J’
Remove items
.
.
items [0] [1] [2] [3] [4]
.
26
&/$667(03/$7('(),1,7,21)2548(8(
WHPSODWHFODVV,WHP7\SH!
FODVV4XH ^
SXEOLF
4XH
4XHLQW PD[ 3$5$0(7(5,=('&216758&725
a4XH '(6758&725
ERRO ,V)XOOFRQVW
ERRO ,V(PSW\FRQVW
YRLG,QVHUW,WHP7\SH QHZ,WHP
YRLG5HPRYH,WHP7\SH ROG,WHP
SULYDWH
LQW IURQW
LQW UHDU
LQW PD[4XH
LQW FRXQW
,WHP7\SH
LWHPV '<1$0,&$55$<,03/(0(17$7,21
`
27
//-----------------------------------------------------------------------
// CLASS TEMPLATE IMPLEMENTATION
//-----------------------------------------------------------------------
template<class ItemType>
Que<ItemType>::Que() // Default Constructor
{
maxQue = 501;
front = 0;
rear = 0;
count = 0;
items = new ItemType[maxQue]; // Dynamic Array
}
template<class ItemType>
Que<ItemType>::~Que( )
{
delete [ ] items; // deallocates array
}
28
template<class ItemType>
Que<ItemType>::Que( int max ) // Parameterized Constructor
{
maxQue = max + 1;
front = 0;
rear = 0;
count = 0;
items = new ItemType[maxQue];
}
template<class ItemType>
bool Que<ItemType>::IsEmpty( ) const
{
return (count == 0);
}
template<class ItemType>
bool Que<ItemType>::IsFull( ) const
{
return ( count == maxQue );
} 29
template<class ItemType>
void Que<ItemType>::Insert( ItemType newItem )
{
if (IsFull())
cout << "OverFlow";
else
{ items[rear] = newItem;
rear = (rear + 1) % maxQue;
++count;
}
}
template<class ItemType>
void Que<ItemType>::Remove( ItemType& oldItem )
{
if (IsEmpty())
cout << "UnderFlow";
else
{ oldItem = items[front];
front = (front + 1) % maxQue;
--count;
} 30
}
Priority Queue
z Sometimes it is not enough just do FIFO
ordering
may want to give some items a higher priority
than other items
– these should be serviced before lower priority even
if they arrived later
31
The Priority Queue
z A Priority queue is a data structure that holds
prioritized items. It is assumed that these items can
be ranked in their order of priority.
z The priority of the elements determine the results of
basic operations.
z An ascending priority queue is a collection of items
from which only the smallest item can be removed.
z A descending priority queue is similar but allows
deletions of only the largest item.
32
Priority Queue Implementation
z Two major ways to implement a priority queue
insert items in a sorted order
– always remove the head
insert in unordered order and search list on remove
– always add to the tail
either way, time is same
– either adding data takes time and removing is quick, or
– adding data is quick and removing takes time
33
The Priority Queue ADT
A Priority Queue is a finite collection of items of type T
on which following operations are defined:
z Initialize the priority queue to be the empty priority
queue.
z Determine whether or not the priority queue is empty.
z Determine whether or not the priority queue is full.
z If priority queue is not full, insert a new item, X, into
the priority queue.
z If priority queue is not empty, remove from the
priority queue an item, X, of highest (or lowest)
priority.
34
Priority Queue Implementation
1 2 3 4 5 6 FRONT REAR
1 AAA 2 2
2 BBB CCC DDD 1 3
3 0 0
4 GGG EEE FFF 5 1
5 HHH 4 4
Each row represents a priority level and acts like a
FIFO Queue.
35
Priority Queue Operations
To delete the first element in a priority queue.
DELPQ (ITEM)
[Find the first non-empty queue]
Find the smallest K such that FRONT[K] != NULL
Delete and return the front element in row K of PQ.
To add an ITEM with priority level K to a priority queue.
INSPQ (ITEM, K)
Insert ITEM as the rear element in row K of PQ.
36
Double-ended-Queue (Deque)
Definition: A deque is a queue in which
elements can be added or removed at either
end but not in the middle.
z There are two variations of a deque:
Input-restricted Deque
allows insertions from one end only.
Output-restricted Deque
allows deletions from one end only.
37
Deque Implementation
A deque is maintained by a circular array with pointers
LEFT and RIGHT, which point to the two ends of the
deque.
We assume that the elements extend from left to right.
A B C D
LEFT = 4
1 2 3 4 5 6 7 8 RIGHT = 7
Y Z W X
LEFT = 7
1 2 3 4 5 6 7 8 RIGHT = 2
38