SlideShare a Scribd company logo
1 of 21
1
Queues
•Definition of a Queue
•Examples of Queues
•Design of a Queue Class
•Different Implementations of the
Queue Class
2
Definition of a Queue
• A queue is a data structure that models/enforces the first-come first-
serve order, or equivalently the first-in first-out (FIFO) order.
• That is, the element that is inserted first into the queue will be the
element that will deleted first, and the element that is inserted last is
deleted last.
• A waiting line is a good real-life example of a queue. (In fact, the
Britich word for “line” is “queue”.)
3
A Graphic Model of a Queue
Tail:
All new items
are added on
this end
Head:
All items are
deleted from
this end
4
Operations on Queues
• Insert(item): (also called enqueue)
• It adds a new item to the tail of the queue
• Remove( ): (also called delete or dequeue)
• It deletes the head item of the queue, and returns to the caller. If the queue is already empty, this
operation returns NULL
• getHead( ):
• Returns the value in the head element of the queue
• getTail( ):
• Returns the value in the tail element of the queue
• isEmpty( )
• Returns true if the queue has no items
• size( )
• Returns the number of items in the queue
5
Examples of Queues
• An electronic mailbox is a queue
• The ordering is chronological (by arrival time)
• A waiting line in a store, at a service counter, on a one-lane road
• Equal-priority processes waiting to run on a processor in a computer
system
6
Queue as a Class
• Much like stacks and linked lists were designed and implemented as
classes, a queue can be conveniently packaged as a class
• It seems natural to think of a queue as similar to a linked list, but with
more basic operations, to enforce the FIFO order of insertion and
deletion
7
A Rough Class for Queue
• class Queue{
public:
typedef int datatype; // datatype is the type of items to be
//added to the queue. By changing int to some other type, the
// queue is easily changed to handle other data types
Queue( );
void enqueue(datatype x);
datatype dequeue( );
datatype peekHead( );
datatype peekTail( );
int size( );
bool isEmpty( );
private:
//A container for items. It’s determined in the implementation
};
8
A Linked List Implementation of the Queue
Class
• The container for items is a linked list, that is, an object of type List
• Let’s call it: List q;
9
A Class for Queue: A Linked List
Implementation
• class Queue{
public:
typedef int datatype;
Queue( ) { };
void enqueue(datatype x) {q.insertTail(x);};
datatype peekHead( ) {assert(size()>0);q.getHead( )->getData( );};
datatype peekTail( ) {assert(size()>0);q.getTail( )->getData( );};
datatype dequeue( ) {assert(size()>0); int x=peekHead( );
q.removeHead( ); return x;};
int size( ) {return q.size( );};
bool isEmpty( ) {return q.isEmpty( );};
private:
List q;
}; // Time: All member functions take O(1) time.
10
A Dynamic-Array Implementation of the Queue
Class
• The container for items is a dynamic array
• It is accomplished as:
datatype *p=new datatype[50];
11
A Class for Queue using Dynamic Arrays
• class Queue{
public:
typedef int datatype;
Queue(int capacity = 50) ;
void enqueue(datatype x); datatype dequeue( );
datatype peekHead( ); datatype peekTail( );
int size( ); bool isEmpty( );
private:
int capacity; // default value is 50
datatype *p; // pointer a dynamic array created by constructor
int length; // number of actual elements in the queue
int head; // index of the head element in the array
int tail; // index of the tail element in the array
};
12
How head and tail Change
• head increases by 1 after each dequeue( )
• tail increases by 1 after each enqueue( )
012474849 4 3
012474849 4 3
012474849 4 3
Now:
After enqueue:
After dequeue:
tail head
tail head
tail head
13
False-Overflow Issue First
• Suppose 50 calls to enqueue have been made, so
now the queue array is full
• Assume 4 calls to dequeue( ) are made
• Assume a call to enqueue( ) is made now. The tail
part seems to have no space, but the front has 4
unused spaces; if never used, they are wasted.
012474849
012474849
34
34
14
Solution: A Circular Queue
• Allow the head (and the tail) to be moving targets
• When the tail end fills up and front part of the array has empty slots,
new insertions should go into the front end
• Next insertion goes into slot 0, and tail tracks it. The insertion after
that goes into a lot 1, etc.
012474849
headtail
34
15
Illustration of Circular Queues
• Current state:
• After One Call to enqueue()
• After One Call to enqueue()
012474849 34
tail
head
012474849 34
tailhead
012474849 34
head tail
16
Numerics for Circular Queues
• head increases by (1 modulo capacity) after each dequeue( ):
head = (head +1) % capacity;
• tail increases by (1 modulo capacity) after each enqueue( ):
tail = (tail +1) % capacity;
17
Complete Implementation of Queues with Dynamic
Arrays
• Show the class structure as a refresher (next slide)
• The implementations of the constructor and member functions will
follow afterwards
18
The Class Structure (revisited)
• class Queue{
public:
typedef int datatype;
Queue(int capacity = 50) ;
void enqueue(datatype x); datatype dequeue( );
datatype peekHead( ); datatype peekTail( );
int size( ); bool isEmpty( );
private:
int capacity; // default value is 50
datatype *p; // pointer a dynamic array created by constructor
int length; // number of actual elements in the queue
int head; // index of the head element in the array
int tail; // index of the tail element in the array
};
19
Implementations of the Members
Queue::Queue(int capacity){
this.capacity = capacity;
p = new datatype[capacity];
length=0; head=0; tail=0;
};
int Queue::size( ){return length;};
bool Queue::isEmpty( ) {return (length==0);};
Queue::datatype Queue::peekHead( ){assert(length>0);return p[head];};
Queue::datatype Queue::peekTail( ){assert(length>0); return p[tail];};
Time: All O(1) time.
20
Implementation enqueue( )
void Queue::enqueue(datatype x){
if (length==0) {p[tail]=x; length++;}
else if (length<capacity) {length++; tail=tail+1 % capacity; p[tail]=x; }
else {// Filled. Create a new array twice big. Copy current array to it. Add x.
datatype *q= new datatype[2*capacity];
int j = head; // copy filled array p (from head to tail) to array q[0…]
for (int i=0;i<capacity;i++) {q[i]=p[j]; j=j+1 % capacity;}
head = 0;
tail = capacity; // pointing to the first empty slot for now
q[tail]=x; // put x in the first empty slot
length++; // account for adding x
capacity = 2*capacity; // reflect that capacity is now doubled
delete [] p; // deletes the old array pointed to by p
p =q; // makes p point to the new array.
}
};
Time: O(1) except at overflow, in which case O(length).
21
Implementation dequeue( )
Queue::datatype Queue::dequeue( ){
assert(length>0);
datatype x= p[head];
head=head+1 % capacity;
return x;
};
Time: O(1).

More Related Content

What's hot

Python advanced 3.the python std lib by example –data structures
Python advanced 3.the python std lib by example –data structuresPython advanced 3.the python std lib by example –data structures
Python advanced 3.the python std lib by example –data structures
John(Qiang) Zhang
 
Python advanced 3.the python std lib by example – algorithm
Python advanced 3.the python std lib by example – algorithmPython advanced 3.the python std lib by example – algorithm
Python advanced 3.the python std lib by example – algorithm
John(Qiang) Zhang
 
CLTL presentation: training an opinion mining system from KAF files using CRF
CLTL presentation: training an opinion mining system from KAF files using CRFCLTL presentation: training an opinion mining system from KAF files using CRF
CLTL presentation: training an opinion mining system from KAF files using CRF
Rubén Izquierdo Beviá
 
Lecture11 standard template-library
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-library
Hariz Mustafa
 
Stacks and queues
Stacks and queuesStacks and queues
Stacks and queues
Abbott
 

What's hot (20)

Stack and queue
Stack and queueStack and queue
Stack and queue
 
Idiomatic C++
Idiomatic C++Idiomatic C++
Idiomatic C++
 
Python advanced 3.the python std lib by example –data structures
Python advanced 3.the python std lib by example –data structuresPython advanced 3.the python std lib by example –data structures
Python advanced 3.the python std lib by example –data structures
 
linked list in c++
linked list in c++linked list in c++
linked list in c++
 
Python advanced 3.the python std lib by example – algorithm
Python advanced 3.the python std lib by example – algorithmPython advanced 3.the python std lib by example – algorithm
Python advanced 3.the python std lib by example – algorithm
 
Queue in Data Structure
Queue in Data StructureQueue in Data Structure
Queue in Data Structure
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
Templates
TemplatesTemplates
Templates
 
Data structure stack&queue basics
Data structure stack&queue   basicsData structure stack&queue   basics
Data structure stack&queue basics
 
강의자료8
강의자료8강의자료8
강의자료8
 
CLTL presentation: training an opinion mining system from KAF files using CRF
CLTL presentation: training an opinion mining system from KAF files using CRFCLTL presentation: training an opinion mining system from KAF files using CRF
CLTL presentation: training an opinion mining system from KAF files using CRF
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
 
Ppt presentation of queues
Ppt presentation of queuesPpt presentation of queues
Ppt presentation of queues
 
Understanding the components of standard template library
Understanding the components of standard template libraryUnderstanding the components of standard template library
Understanding the components of standard template library
 
Java generics
Java genericsJava generics
Java generics
 
Lecture11 standard template-library
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-library
 
Stacks and queues
Stacks and queuesStacks and queues
Stacks and queues
 
Chapter 6 ds
Chapter 6 dsChapter 6 ds
Chapter 6 ds
 
C++ STL 概觀
C++ STL 概觀C++ STL 概觀
C++ STL 概觀
 

Similar to Queues

Queue ADT for data structure for computer
Queue ADT for data structure for computerQueue ADT for data structure for computer
Queue ADT for data structure for computer
abinathsabi
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
RAtna29
 

Similar to Queues (20)

Queue ADT for data structure for computer
Queue ADT for data structure for computerQueue ADT for data structure for computer
Queue ADT for data structure for computer
 
basics of queues
basics of queuesbasics of queues
basics of queues
 
9 python data structure-2
9 python data structure-29 python data structure-2
9 python data structure-2
 
Queue
QueueQueue
Queue
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
Data Structures and Files
Data Structures and FilesData Structures and Files
Data Structures and Files
 
Queue
QueueQueue
Queue
 
Data Structures - Lecture 6 [queues]
Data Structures - Lecture 6 [queues]Data Structures - Lecture 6 [queues]
Data Structures - Lecture 6 [queues]
 
Stack in Sata Structure
Stack in Sata StructureStack in Sata Structure
Stack in Sata Structure
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
 
Queues
Queues Queues
Queues
 
DSA-Day-2-PS.pptx
DSA-Day-2-PS.pptxDSA-Day-2-PS.pptx
DSA-Day-2-PS.pptx
 
CEN 235 4. Abstract Data Types - Queue and Stack.pdf
CEN 235 4. Abstract Data Types - Queue and Stack.pdfCEN 235 4. Abstract Data Types - Queue and Stack.pdf
CEN 235 4. Abstract Data Types - Queue and Stack.pdf
 
02 stackqueue
02 stackqueue02 stackqueue
02 stackqueue
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
 
Ch03_stacks_and_queues.ppt
Ch03_stacks_and_queues.pptCh03_stacks_and_queues.ppt
Ch03_stacks_and_queues.ppt
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
justbasics.pdf
justbasics.pdfjustbasics.pdf
justbasics.pdf
 
stacks and queues class 12 in c++
stacks and  queues class 12 in c++stacks and  queues class 12 in c++
stacks and queues class 12 in c++
 
Unit 4 queue
Unit   4 queueUnit   4 queue
Unit 4 queue
 

More from Syed Zaid Irshad

Basic Concept of Information Technology
Basic Concept of Information TechnologyBasic Concept of Information Technology
Basic Concept of Information Technology
Syed Zaid Irshad
 
Introduction to ICS 1st Year Book
Introduction to ICS 1st Year BookIntroduction to ICS 1st Year Book
Introduction to ICS 1st Year Book
Syed Zaid Irshad
 

More from Syed Zaid Irshad (20)

Operating System.pdf
Operating System.pdfOperating System.pdf
Operating System.pdf
 
DBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_SolutionDBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_Solution
 
Data Structure and Algorithms.pptx
Data Structure and Algorithms.pptxData Structure and Algorithms.pptx
Data Structure and Algorithms.pptx
 
Design and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxDesign and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptx
 
Professional Issues in Computing
Professional Issues in ComputingProfessional Issues in Computing
Professional Issues in Computing
 
Reduce course notes class xi
Reduce course notes class xiReduce course notes class xi
Reduce course notes class xi
 
Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xii
 
Introduction to Database
Introduction to DatabaseIntroduction to Database
Introduction to Database
 
C Language
C LanguageC Language
C Language
 
Flowchart
FlowchartFlowchart
Flowchart
 
Algorithm Pseudo
Algorithm PseudoAlgorithm Pseudo
Algorithm Pseudo
 
Computer Programming
Computer ProgrammingComputer Programming
Computer Programming
 
ICS 2nd Year Book Introduction
ICS 2nd Year Book IntroductionICS 2nd Year Book Introduction
ICS 2nd Year Book Introduction
 
Security, Copyright and the Law
Security, Copyright and the LawSecurity, Copyright and the Law
Security, Copyright and the Law
 
Computer Architecture
Computer ArchitectureComputer Architecture
Computer Architecture
 
Data Communication
Data CommunicationData Communication
Data Communication
 
Information Networks
Information NetworksInformation Networks
Information Networks
 
Basic Concept of Information Technology
Basic Concept of Information TechnologyBasic Concept of Information Technology
Basic Concept of Information Technology
 
Introduction to ICS 1st Year Book
Introduction to ICS 1st Year BookIntroduction to ICS 1st Year Book
Introduction to ICS 1st Year Book
 
Using the set operators
Using the set operatorsUsing the set operators
Using the set operators
 

Recently uploaded

Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
dharasingh5698
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
MsecMca
 

Recently uploaded (20)

Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Unit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfUnit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdf
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 

Queues

  • 1. 1 Queues •Definition of a Queue •Examples of Queues •Design of a Queue Class •Different Implementations of the Queue Class
  • 2. 2 Definition of a Queue • A queue is a data structure that models/enforces the first-come first- serve order, or equivalently the first-in first-out (FIFO) order. • That is, the element that is inserted first into the queue will be the element that will deleted first, and the element that is inserted last is deleted last. • A waiting line is a good real-life example of a queue. (In fact, the Britich word for “line” is “queue”.)
  • 3. 3 A Graphic Model of a Queue Tail: All new items are added on this end Head: All items are deleted from this end
  • 4. 4 Operations on Queues • Insert(item): (also called enqueue) • It adds a new item to the tail of the queue • Remove( ): (also called delete or dequeue) • It deletes the head item of the queue, and returns to the caller. If the queue is already empty, this operation returns NULL • getHead( ): • Returns the value in the head element of the queue • getTail( ): • Returns the value in the tail element of the queue • isEmpty( ) • Returns true if the queue has no items • size( ) • Returns the number of items in the queue
  • 5. 5 Examples of Queues • An electronic mailbox is a queue • The ordering is chronological (by arrival time) • A waiting line in a store, at a service counter, on a one-lane road • Equal-priority processes waiting to run on a processor in a computer system
  • 6. 6 Queue as a Class • Much like stacks and linked lists were designed and implemented as classes, a queue can be conveniently packaged as a class • It seems natural to think of a queue as similar to a linked list, but with more basic operations, to enforce the FIFO order of insertion and deletion
  • 7. 7 A Rough Class for Queue • class Queue{ public: typedef int datatype; // datatype is the type of items to be //added to the queue. By changing int to some other type, the // queue is easily changed to handle other data types Queue( ); void enqueue(datatype x); datatype dequeue( ); datatype peekHead( ); datatype peekTail( ); int size( ); bool isEmpty( ); private: //A container for items. It’s determined in the implementation };
  • 8. 8 A Linked List Implementation of the Queue Class • The container for items is a linked list, that is, an object of type List • Let’s call it: List q;
  • 9. 9 A Class for Queue: A Linked List Implementation • class Queue{ public: typedef int datatype; Queue( ) { }; void enqueue(datatype x) {q.insertTail(x);}; datatype peekHead( ) {assert(size()>0);q.getHead( )->getData( );}; datatype peekTail( ) {assert(size()>0);q.getTail( )->getData( );}; datatype dequeue( ) {assert(size()>0); int x=peekHead( ); q.removeHead( ); return x;}; int size( ) {return q.size( );}; bool isEmpty( ) {return q.isEmpty( );}; private: List q; }; // Time: All member functions take O(1) time.
  • 10. 10 A Dynamic-Array Implementation of the Queue Class • The container for items is a dynamic array • It is accomplished as: datatype *p=new datatype[50];
  • 11. 11 A Class for Queue using Dynamic Arrays • class Queue{ public: typedef int datatype; Queue(int capacity = 50) ; void enqueue(datatype x); datatype dequeue( ); datatype peekHead( ); datatype peekTail( ); int size( ); bool isEmpty( ); private: int capacity; // default value is 50 datatype *p; // pointer a dynamic array created by constructor int length; // number of actual elements in the queue int head; // index of the head element in the array int tail; // index of the tail element in the array };
  • 12. 12 How head and tail Change • head increases by 1 after each dequeue( ) • tail increases by 1 after each enqueue( ) 012474849 4 3 012474849 4 3 012474849 4 3 Now: After enqueue: After dequeue: tail head tail head tail head
  • 13. 13 False-Overflow Issue First • Suppose 50 calls to enqueue have been made, so now the queue array is full • Assume 4 calls to dequeue( ) are made • Assume a call to enqueue( ) is made now. The tail part seems to have no space, but the front has 4 unused spaces; if never used, they are wasted. 012474849 012474849 34 34
  • 14. 14 Solution: A Circular Queue • Allow the head (and the tail) to be moving targets • When the tail end fills up and front part of the array has empty slots, new insertions should go into the front end • Next insertion goes into slot 0, and tail tracks it. The insertion after that goes into a lot 1, etc. 012474849 headtail 34
  • 15. 15 Illustration of Circular Queues • Current state: • After One Call to enqueue() • After One Call to enqueue() 012474849 34 tail head 012474849 34 tailhead 012474849 34 head tail
  • 16. 16 Numerics for Circular Queues • head increases by (1 modulo capacity) after each dequeue( ): head = (head +1) % capacity; • tail increases by (1 modulo capacity) after each enqueue( ): tail = (tail +1) % capacity;
  • 17. 17 Complete Implementation of Queues with Dynamic Arrays • Show the class structure as a refresher (next slide) • The implementations of the constructor and member functions will follow afterwards
  • 18. 18 The Class Structure (revisited) • class Queue{ public: typedef int datatype; Queue(int capacity = 50) ; void enqueue(datatype x); datatype dequeue( ); datatype peekHead( ); datatype peekTail( ); int size( ); bool isEmpty( ); private: int capacity; // default value is 50 datatype *p; // pointer a dynamic array created by constructor int length; // number of actual elements in the queue int head; // index of the head element in the array int tail; // index of the tail element in the array };
  • 19. 19 Implementations of the Members Queue::Queue(int capacity){ this.capacity = capacity; p = new datatype[capacity]; length=0; head=0; tail=0; }; int Queue::size( ){return length;}; bool Queue::isEmpty( ) {return (length==0);}; Queue::datatype Queue::peekHead( ){assert(length>0);return p[head];}; Queue::datatype Queue::peekTail( ){assert(length>0); return p[tail];}; Time: All O(1) time.
  • 20. 20 Implementation enqueue( ) void Queue::enqueue(datatype x){ if (length==0) {p[tail]=x; length++;} else if (length<capacity) {length++; tail=tail+1 % capacity; p[tail]=x; } else {// Filled. Create a new array twice big. Copy current array to it. Add x. datatype *q= new datatype[2*capacity]; int j = head; // copy filled array p (from head to tail) to array q[0…] for (int i=0;i<capacity;i++) {q[i]=p[j]; j=j+1 % capacity;} head = 0; tail = capacity; // pointing to the first empty slot for now q[tail]=x; // put x in the first empty slot length++; // account for adding x capacity = 2*capacity; // reflect that capacity is now doubled delete [] p; // deletes the old array pointed to by p p =q; // makes p point to the new array. } }; Time: O(1) except at overflow, in which case O(length).
  • 21. 21 Implementation dequeue( ) Queue::datatype Queue::dequeue( ){ assert(length>0); datatype x= p[head]; head=head+1 % capacity; return x; }; Time: O(1).