Upload
shrey-khokhawat
View
227
Download
0
Embed Size (px)
Citation preview
8/8/2019 Chapter 05 Queues
1/23
Chapter 5: QueuesDefn. As a data structure, a queue is an ordered collect ion of data
items w ith the property that items can be removed only at oneend, called the front of the queue, and items can be added only atthe other end, called the back of the queue. Bas ic operat ions are:
construct: Create an empty queueempty: Check if a queue is emptyaddQ: Add a value at the back of the queue
front: Retr ieve the value at the front of the queueremoveQ: Remove the value at the front of the queue
Whereas a stack is a Last-In-F irst-Out (LIFO) structure, a queue is aFirst-In-First-Out (FIFO ) or First-Come-First-Served (FCFS )structure.
Q ueue :Front: Remove ONLYBack: Add ONLY
8/8/2019 Chapter 05 Queues
2/23
a. I/O buffers: queues, scrolls, dequesj From a f ile: ( queue )
Infile >> X;
X
InputBuff er
CPU
MemoryDisk
Input Buffer
queues input for the CPU
Ex amples:
8/8/2019 Chapter 05 Queues
3/23
cin >> X;
Keyboard
X
InputBuffer
Memory
Scroll :Front: Remove ONLYBack: Add
or
Remove (Backspace)
Backspace
Interactively: (scroll queue o n o neend, stack o n the other)
8/8/2019 Chapter 05 Queues
4/23
Scroll :Front: Remove
or Add
Back: Addor
Remove
S creen handling: (deque double-ended qu eu e)
8/8/2019 Chapter 05 Queues
5/23
j Pr inter queue: When f iles are subm itted to a pr inter, they are
placed in the pr inter queue. The pr inter software executesan algor ithm someth ing l ike:
for (;;){
while (printerQueue.empty())sleep 1;
printFile = printerQueue.removeQ();Print(printFile);
}
b. S cheduling queues in a multi-user computer system:
8/8/2019 Chapter 05 Queues
6/23
1. Res ident queue: On d isk, wa iting for memory
2. Ready queue: In memory has everyth ing it needs to run,except the CPU
3. Suspended queue: Wa iting for I/O transfer or to be reass igned the CPU
1
2
3
O ther Queues:
8/8/2019 Chapter 05 Queues
7/23
Probably uses a p riori ty queue : Items w ith lower
pr ior ity are beh ind all thosewith h igher pr ior ity.(Usually a new item isinserted beh ind those w ith thesame pr ior ity.)
c. CPU S cheduling:
8/8/2019 Chapter 05 Queues
8/23
Queues vs. S tacksStacks are a LIFO conta iner
Store data in the reverse of order rece ivedQueues are a FIFO conta iner
Store data in the order rece ived
Stacks then suggest appl icat ions where some sort of reversalor unw ind ing is des ired.
Queues suggest appl icat ions where serv ice is to be renderedrelat ive to order rece ived.Stacks and Queues can be used in conjunct ion to compare
different order ings of the same data set.From an order ing perspect ive, then, Queues are the oppos ite
of stacksEasy solut ion to the pal indrome problem
8/8/2019 Chapter 05 Queues
9/23
E asy Palindr ome Check# include Stack.h;
# include Queue.h;# include using namespace std;int main(){
Stack S;Queue Q;char ch;
cout > ch){S.push(ch);Q.addq(ch);
}
bool pal = true;
while (!Q.empty() && pal) {pal = Q.front() == S.pop() ;Q.removeq() ;
}if (pal)
cout
8/8/2019 Chapter 05 Queues
10/23
Array ImplementationAny implementat ion of a queue requ ires:storage for the data as well as
markers (po inters) for the front and for the back of the queue.
An array-based implementat ion would need structures l ikemyArray , an array to store the elements of the queuemyFront , an index to track the front queue elementmyBack , an index to track the pos ition following last queue element
Additions to the queue would result in increment ing myBack .
Deletions from the queue would result in increment ing myFront .Clearly, wed run out of space soon!
Solut ions include:Sh ifting the elements downward w ith each delet ion (YUCK!!)View ing array as a c ircular buffer, i.e. wrapp ing the end to the front
8/8/2019 Chapter 05 Queues
11/23
Circular Array-ImplementationW raparound keeps the add ition/delet ion cycle from walk ing off the edge of thestorage array.
Say, myArray has QUEUE_CAPACITY elements.
When myBack hits the end of myArray , a delet ion should wrap myBack aroundto the f irst element of myArray , viz:
myBack++;if (myBack = = QUEUE_CAPACITY)
myBack = 0;
//equivalently (preferred, concise)myBack = (myBack + 1) % QUEUE_CAPACITY;
Analogous handl ing of myFront needed.
8/8/2019 Chapter 05 Queues
12/23
Circular Array-Implementation II
Initially, a queue object is empty.myFront = = 0myBack = = 0
After many insert ions and delet ions, the queue is fullFirst element, say, at myArray[i]
myFront has value of i.Last element then at myArray[i-1] (i > 0)
myBack has value of i.
PROBL EM : H ow to distinguish between empty & full???Some Common Solut ions:1. Keep an empty slot between myFront and myBack ,
i.e., myArray uses QUEUE_CAPACITY - 1 elements2. Keep an integer counter to track actual number of elements in queue3. Keep a boolean full var iable to keep track of if queue is full or not
myBack : I ncremented when an item is ADD ED myFront : I ncremented when an item is R EM OV ED
8/8/2019 Chapter 05 Queues
13/23
QUEUE class#ifndef QUEUE#define QUEUEconst int QUEUE_CAPACITY = 128;typedef int QueueElement;class Queue{
/***** Function Members *****/
public:Queue();bool empty() const;bool full() const;void addQ(const QueueElement & value);QueueElement front const(); //nondestructive peekvoid removeQ();
/***** Data Members *****/private:QueueElement myArray[QUEUE_CAPACITY];int myFront,
myBack;}; // end of class declaration#endif
8/8/2019 Chapter 05 Queues
14/23
QUEUE class implementationQueue::Queue(){
myFront = myBack = 0;}
bool Queue::empty(){return myFront == myBack;
}
bool Queue::full(){
return myFront == (myBack + 1) % QUEUE_CAPACITY;}
8/8/2019 Chapter 05 Queues
15/23
QUEUE class implementation IIv oid Queue::addQ(const QueueElement& v alue){
if (myFront != (myBack + 1) % QUEUE_CAPACITY){
myArray[myBack] = v alue;myBack = (myBack + 1) % QUEUE_CAPACITY;
}return;}
v oid Queue::remo v eQ(){
myFront = (myFront + 1) % QUEUE_CAPACITY;}
8/8/2019 Chapter 05 Queues
16/23
Linked list implementationLinked l ist implementat ion is another approach for queue representat ion.
The interface to the class Queueempty, addq, removeq, front , etc. would ot chang e
The storage structure would be a l inked l ist.The markers would be pointers now rather than ind ices into an array.
myFront would conta in the address of the first node in th is listmyBack would conta in the address of the last node in th is list
empty would test if myFront was a nonnull po inter ,addq would allocate a new node, l ink it off myBack and update myBack,removeq would remove the f irst element and update myFront,front would return a copy of the element whose address was in myFront
8/8/2019 Chapter 05 Queues
17/23
equeA deque (double-ended queue) is similar to a queueBUT additions and deletions may be performed on either end .
H enc e, an im p leme n ta tion needs a dire ctive (t ag) indi ca ting a t wha t end the op er a tion is to be p er f ormed OR mul tip le me thods should be p rovided.
We mod ify a queue's c ircular array implementat ion here.
# include using namespace std;
enum where {front, rear};
/* Deque implemented with same data membersmyArraymyFrontmyBack
Constructors and empty(), full() methods the same*/
8/8/2019 Chapter 05 Queues
18/23
eque enqueuingvoid Deque::addQ(int item, where w){
if ((myBack +1)% QUEUE_CAPACITY == myFront)cout
8/8/2019 Chapter 05 Queues
19/23
eque enqueuing/ /better to pro
ide two addition methods v o id Deque::push_fr o nt( int i tem){ if ((myBack +1)% QUEUE_CAPACITY == myFront)
cout
8/8/2019 Chapter 05 Queues
20/23
8/8/2019 Chapter 05 Queues
21/23
deque s
The deque is a standard conta iner prov ided by STL.
It is eas ily implemented by the vector type.
See chapter 6 for more deta ils.
8/8/2019 Chapter 05 Queues
22/23
Priority Queues P riority queues are queues in wh ich items are ordered by priority
rather than temporally (i.e. order
in wh
ich rece
ived).
Any queue implementat ion then can be taken and mod if ied to acqu irea pr ior ity queue.
The only needed mod if icat ion is the addq() method.
Instead of uncond itionally add ing to the back, the queue must bescanned for the correct insert ion po int.
An array implementat ion then would requ ire sh ifting elements(YUCK).
Hence a l inked l ist implementat ion is preferred.
(Develop then the preferred solut ion after chapter 8)
8/8/2019 Chapter 05 Queues
23/23
Priority Queuesc l a s s P r i o r i t y Q{
p u b l i c :P r i o r i t y Q ( ) ;
o i d a d d q ( i n t ) ;i n t r e m o e q ( ) ;
b o o l e m p t y ( ) ;b o o l f u l l ( ) ;
i n t b a c k ( ) ;i n t s i z e ( ) ;
p r i a t e :c o n s t i n t P R I O R I T Y Q _ C A PA C I T Y = s o m e _ a l u e ;i n t m y A r r a y [ P R I O R I T Y Q _ C A P A C I T Y ] ;
i n t m y F r o n t ;i n t m y B a c k ;} ;