SlideShare a Scribd company logo
1 of 25
Queue
Queue Overview
• Queue ADT
• Basic operations of queue
– Push (or Enqueue), Pop (or Dequeue) etc.
• Implementations of queue using
– array
– linked list
Queue
• How to include a new person/item?
• How to remove a particular person/item?
Queue
• Collection of items into which items
may be added from rear end and
from which items may be removed
from the front end
The Queue ADT
• Fundamental operations:
– Enqueue: Equivalent to an insert
– Dequeue: Deletes the element from rear end
– isEmpty: Returns true if there are no elements in the queue
– ReadFront: Examines the element at the front of the queue
– ReadRear: Examines the elements at the rear of the queue
Enqueue and Dequeue
Queue ADT Specification
Structure: Elements are added to one end and removed from the other end.
Definitions: (Provided by user):
MAX_ITEMS: Maximum number of items that might be on the queue.
Item Type: Data type of the items on the queue.
Operations: (Provided by the ADT):
MakeEmpty
Functions: Sets queue to an empty state.
Preconditions: None
PostCondition: Queue is empty.
Boolean IsEmpty
Functions: Determine whether the queue is empty.
Preconditions: Queue has been initialized.
PostCondition: Function value = (queue is empty)
Boolean IsFull
Functions: Determine whether the queue is full.
Preconditions: Queue has been initialized.
PostCondition: Function value = (queue is full)
Enqueue (ItemType newItem)
Functions: Add newItem at the rear of the queue.
Preconditions: Queue has been initialized and is not full.
PostCondition: newItem at the rear of the queue.
Dequeue (ItemType& item)
Functions: Remove tem from front of queue and returns it in item.
Preconditions: Queue has been initialized and is not empty.
PostCondition: The element at front has been removed from the queue.
Item is copy of removed element.
Queue ADT
• Queue is known as FIFO (First In, First Out) lists.
– The last element inserted will be the last to be retrieved
Implementation of Queue
• Any list implementation could be used to implement a queue
– Arrays (static: the size of queue is given initially)
– Linked lists (dynamic: never become full, except when memory
overflows)
• We will explore implementations based on array and linked list
• Let’s see how to use an array to implement a queue first
Array Implementation
• Need to declare an array size ahead of time
• Associated with each queue are front and rear
– for an empty queue, set front and rear to -1
• enqueue (X)
– (1) Increment front by 1 if front = -1
– (2) Increment rear by 1
– (3) Set queue[rear] = X
• dequeue
– (1) Delete value to queue[front]
– (2) Increment front by 1
• These operations are performed in constant time?
Queue class
• Attributes of Queue
– capacity: the max size of queue
– rear: the index of the last element of queue
– front: the index of the first element of queue
– values: point to an array which stores elements of queue
• Operations of Queue
– IsEmpty: return true if queue is empty, return false
otherwise
– isFull: return true if queue is full, return false otherwise
– readFront: return the element at the front of queue
– readRear: return the element at the rear of queue
– enqueue: add an element to the rear of queue
– dequeue: delete the element from the front of queue
– displayQueue: print all the data in the queue
Implementing a Queue Class
• Define data members: consider storage structure(s)
• Attempt #1: Use an array with the rear and front equal to -1
e.g., Enqueue 75, Enqueue 89, Enqueue 64, …
front rear
75 89 64
[0] [1] [2] [3] [4]
• … Dequeue
front rear
89 64
[0] [1] [2] [3] [4]
front rear
89 64
[0] [1] [2] [3] [4]
Dequeue
(1) Delete queue[front]
(2) Increment front by 1
Problem?
front rear
89 64
[0] [1] [2] [3] [4]
OR
front rear
89 64
[0] [1] [2] [3] [4]
Dequeue ??????
(1) Delete value of queue[front]
(2) Increment front by 1?????
Queue class
class Queue {
public:
Queue(int size = 10); // constructor
~Queue() { delete [] values; } // destructor
bool isEmpty() { return rear == -1; }
bool isFull() { return (rear-front) == maxRear; }
double readFront();
double readRear();
void enqueue(double x);
void dequeue();
void displayQueue();
private:
int maxRear; // maxRear = capacity - 1
int rear; // index of currently inserted value
int front; // index of next element to be deleted
double [] values; // element array
};
Create Queue
• The constructor of Queue
– Allocate an array of size. By default,
size = 10.
– When the queue is full, rear will have its maximum
value, i.e. capacity – 1.
– Initially rear is set to -1. It means the queue is empty.
Queue::Queue(int capacity /*= 10*/) {
if(capacity<1) {
cout<<“cannot create queue of size below 1”;
return;
}
maxRear= capacity - 1;
values = new double[capacity];
front = rear = -1;
}
Although the constructor
dynamically allocates the queue
array, the queue is still static. The
size is fixed after the initialization.
Enqueue
• void Enqueue(double x);
– Add an element to the queue
– If the queue is full, print the error information.
– Note rear always represents the index of the
recently added element. Before adding an element,
increment rear.
void Queue::enqueue(const double x) {
if (IsFull())
cout << "Error: the queue is full." << endl;
else
values[++rear] = x; //is it correct?
}
Dequeue
• double dequeue()
– Removes and return the element at the front of the queue
– If the queue is empty, print the error information. (In this
case, the return value is useless.)
– Don’t forgot to shift all elements to left and modify rear
void Queue::dequeue() {
if (IsEmpty()) {
cout << "Error: the queue is empty." << endl;
return;
}
else {
shiftElementsLeft();
//rear???
}
}
Queue Rear
• double readRear()
– Return the element at rear of the queue
– Unlike dequeue, this function does not remove
the element
double Queue::readRear() {
if (IsEmpty()) {
cout << "Error: the queue is empty." << endl;
return -1;
}
else
return values[rear];
}
Queue Front
• double readFront()
– Return the element at front of the queue
– Unlike dequeue, this function does not remove
the element
double Queue::readFront() {
if (IsEmpty()) {
cout << "Error: the queue is empty." << endl;
return -1;
}
else
return values[front];
}
Using Queue
int main(void) {
Queue q(5);
q.enqueue(5.0);
q.enqueue(6.5);
q.enqueue(-3.0);
q.enqueue(-8.0);
q.displayQueue();
cout << “Front: " << q.getFront() << endl;
cout << “Rear: " << q.getRear() << endl;
q.dequeue();
cout << “Rear: " << q.getRear() << endl;
cout << “Front: " << q.getFront() << endl;
while (!q.isEmpty()) q.dequeue();
q.displayQueue();
return 0;
}
Result????
Circular Queue
Circular Queue
• enqueue(X)?
• dequeue()?
• isEmpty()?
• isFull()?
• Constructor?
• readFront()?
• readRear()?
Circular Queue
• Enqueue(X)?rear = (rear+1)%capacity; values[rear]=x;
• Dequeue()?if (!isEmpty()){front = (front+1)%capacity; return
values[front]}
• isEmpty()? return front == rear;
• isFull()? return ((rear+1)%capacity) == front;
• Constructor? set front = rear = 0
• readFront()?  if (!isEmpty()){return values[(front+1)%capacity];}
• readRear()?  if (!isEmpty()){return values[rear];}
Circular Queue
• Alternate implementation?
• Any modification in Queue class?
– elementCount or currentSize??
References
• Data Structures and Algorithms, LUMS

More Related Content

What's hot (20)

QUEUE IN DATA STRUCTURE USING C
QUEUE IN DATA STRUCTURE USING CQUEUE IN DATA STRUCTURE USING C
QUEUE IN DATA STRUCTURE USING C
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority QueueWhat is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
 
Queues
QueuesQueues
Queues
 
Detalied information of queue
Detalied information of queueDetalied information of queue
Detalied information of queue
 
Queues
QueuesQueues
Queues
 
My lectures circular queue
My lectures circular queueMy lectures circular queue
My lectures circular queue
 
Queue
QueueQueue
Queue
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
 
Team 6
Team 6Team 6
Team 6
 
Algorithm: priority queue
Algorithm: priority queueAlgorithm: priority queue
Algorithm: priority queue
 
Data Structure (Queue)
Data Structure (Queue)Data Structure (Queue)
Data Structure (Queue)
 
Queue
QueueQueue
Queue
 
Queue in Data Structure
Queue in Data StructureQueue in Data Structure
Queue in Data Structure
 
Queue
QueueQueue
Queue
 
Priority queues
Priority queuesPriority queues
Priority queues
 
Queue
QueueQueue
Queue
 
Queues in C++
Queues in C++Queues in C++
Queues in C++
 
Queue
QueueQueue
Queue
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 

Similar to Queue (20)

LEC4-DS ALGO.pdf
LEC4-DS  ALGO.pdfLEC4-DS  ALGO.pdf
LEC4-DS ALGO.pdf
 
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
 
Queues
Queues Queues
Queues
 
Unit – iv queue
Unit – iv    queueUnit – iv    queue
Unit – iv queue
 
Data Structures and Files
Data Structures and FilesData Structures and Files
Data Structures and Files
 
Queues.ppt
Queues.pptQueues.ppt
Queues.ppt
 
Ch03_stacks_and_queues.ppt
Ch03_stacks_and_queues.pptCh03_stacks_and_queues.ppt
Ch03_stacks_and_queues.ppt
 
stacks and queues for public
stacks and queues for publicstacks and queues for public
stacks and queues for public
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
 
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
 
Ist year Msc,2nd sem module1
Ist year Msc,2nd sem module1Ist year Msc,2nd sem module1
Ist year Msc,2nd sem module1
 
Lecture 2d queues
Lecture 2d queuesLecture 2d queues
Lecture 2d queues
 
Queue(lecture8).pptx
Queue(lecture8).pptxQueue(lecture8).pptx
Queue(lecture8).pptx
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
QUEUE.pptx
QUEUE.pptxQUEUE.pptx
QUEUE.pptx
 
Data Structures by Maneesh Boddu
Data Structures by Maneesh BodduData Structures by Maneesh Boddu
Data Structures by Maneesh Boddu
 
2 b queues
2 b queues2 b queues
2 b queues
 
Data Structures 2
Data Structures 2Data Structures 2
Data Structures 2
 
05-stack_queue.ppt
05-stack_queue.ppt05-stack_queue.ppt
05-stack_queue.ppt
 
2.1 STACK & QUEUE ADTS
2.1 STACK & QUEUE ADTS2.1 STACK & QUEUE ADTS
2.1 STACK & QUEUE ADTS
 

More from Ayaz Akhtar

Boiler presentation
Boiler presentationBoiler presentation
Boiler presentationAyaz Akhtar
 
Diabetes clinical
Diabetes clinicalDiabetes clinical
Diabetes clinicalAyaz Akhtar
 
Trw presentation,
Trw presentation,Trw presentation,
Trw presentation,Ayaz Akhtar
 
managers and management
 managers and management managers and management
managers and managementAyaz Akhtar
 
Concept nature and principles of management
Concept nature and principles of managementConcept nature and principles of management
Concept nature and principles of managementAyaz Akhtar
 
Continuous casting of billets
Continuous casting of billetsContinuous casting of billets
Continuous casting of billetsAyaz Akhtar
 

More from Ayaz Akhtar (12)

Boiler presentation
Boiler presentationBoiler presentation
Boiler presentation
 
Conjunctivitis
ConjunctivitisConjunctivitis
Conjunctivitis
 
Common cold
Common coldCommon cold
Common cold
 
Diabetes clinical
Diabetes clinicalDiabetes clinical
Diabetes clinical
 
Trw presentation,
Trw presentation,Trw presentation,
Trw presentation,
 
Malaria
MalariaMalaria
Malaria
 
Drug laws
Drug lawsDrug laws
Drug laws
 
Meningitis
MeningitisMeningitis
Meningitis
 
Rabies
RabiesRabies
Rabies
 
managers and management
 managers and management managers and management
managers and management
 
Concept nature and principles of management
Concept nature and principles of managementConcept nature and principles of management
Concept nature and principles of management
 
Continuous casting of billets
Continuous casting of billetsContinuous casting of billets
Continuous casting of billets
 

Recently uploaded

internship thesis pakistan aeronautical complex kamra
internship thesis pakistan aeronautical complex kamrainternship thesis pakistan aeronautical complex kamra
internship thesis pakistan aeronautical complex kamraAllTops
 
Beyond the Codes_Repositioning towards sustainable development
Beyond the Codes_Repositioning towards sustainable developmentBeyond the Codes_Repositioning towards sustainable development
Beyond the Codes_Repositioning towards sustainable developmentNimot Muili
 
Marketing Management 16th edition by Philip Kotler test bank.docx
Marketing Management 16th edition by Philip Kotler test bank.docxMarketing Management 16th edition by Philip Kotler test bank.docx
Marketing Management 16th edition by Philip Kotler test bank.docxssuserf63bd7
 
Reviewing and summarization of university ranking system to.pptx
Reviewing and summarization of university ranking system  to.pptxReviewing and summarization of university ranking system  to.pptx
Reviewing and summarization of university ranking system to.pptxAss.Prof. Dr. Mogeeb Mosleh
 
Safety T fire missions army field Artillery
Safety T fire missions army field ArtillerySafety T fire missions army field Artillery
Safety T fire missions army field ArtilleryKennethSwanberg
 
The Psychology Of Motivation - Richard Brown
The Psychology Of Motivation - Richard BrownThe Psychology Of Motivation - Richard Brown
The Psychology Of Motivation - Richard BrownSandaliGurusinghe2
 
Leaders enhance communication by actively listening, providing constructive f...
Leaders enhance communication by actively listening, providing constructive f...Leaders enhance communication by actively listening, providing constructive f...
Leaders enhance communication by actively listening, providing constructive f...Ram V Chary
 
Dealing with Poor Performance - get the full picture from 3C Performance Mana...
Dealing with Poor Performance - get the full picture from 3C Performance Mana...Dealing with Poor Performance - get the full picture from 3C Performance Mana...
Dealing with Poor Performance - get the full picture from 3C Performance Mana...Hedda Bird
 
Strategic Management, Vision Mission, Internal Analsysis
Strategic Management, Vision Mission, Internal AnalsysisStrategic Management, Vision Mission, Internal Analsysis
Strategic Management, Vision Mission, Internal Analsysistanmayarora45
 
How Software Developers Destroy Business Value.pptx
How Software Developers Destroy Business Value.pptxHow Software Developers Destroy Business Value.pptx
How Software Developers Destroy Business Value.pptxAaron Stannard
 
W.H.Bender Quote 62 - Always strive to be a Hospitality Service professional
W.H.Bender Quote 62 - Always strive to be a Hospitality Service professionalW.H.Bender Quote 62 - Always strive to be a Hospitality Service professional
W.H.Bender Quote 62 - Always strive to be a Hospitality Service professionalWilliam (Bill) H. Bender, FCSI
 
Independent Escorts Vikaspuri / 9899900591 High Profile Escort Service in Delhi
Independent Escorts Vikaspuri  / 9899900591 High Profile Escort Service in DelhiIndependent Escorts Vikaspuri  / 9899900591 High Profile Escort Service in Delhi
Independent Escorts Vikaspuri / 9899900591 High Profile Escort Service in Delhiguptaswati8536
 
International Ocean Transportation p.pdf
International Ocean Transportation p.pdfInternational Ocean Transportation p.pdf
International Ocean Transportation p.pdfAlejandromexEspino
 
digital Human resource management presentation.pdf
digital Human resource management presentation.pdfdigital Human resource management presentation.pdf
digital Human resource management presentation.pdfArtiSrivastava23
 
Agile Coaching Change Management Framework.pptx
Agile Coaching Change Management Framework.pptxAgile Coaching Change Management Framework.pptx
Agile Coaching Change Management Framework.pptxalinstan901
 

Recently uploaded (17)

internship thesis pakistan aeronautical complex kamra
internship thesis pakistan aeronautical complex kamrainternship thesis pakistan aeronautical complex kamra
internship thesis pakistan aeronautical complex kamra
 
Beyond the Codes_Repositioning towards sustainable development
Beyond the Codes_Repositioning towards sustainable developmentBeyond the Codes_Repositioning towards sustainable development
Beyond the Codes_Repositioning towards sustainable development
 
Intro_University_Ranking_Introduction.pptx
Intro_University_Ranking_Introduction.pptxIntro_University_Ranking_Introduction.pptx
Intro_University_Ranking_Introduction.pptx
 
Marketing Management 16th edition by Philip Kotler test bank.docx
Marketing Management 16th edition by Philip Kotler test bank.docxMarketing Management 16th edition by Philip Kotler test bank.docx
Marketing Management 16th edition by Philip Kotler test bank.docx
 
Reviewing and summarization of university ranking system to.pptx
Reviewing and summarization of university ranking system  to.pptxReviewing and summarization of university ranking system  to.pptx
Reviewing and summarization of university ranking system to.pptx
 
Safety T fire missions army field Artillery
Safety T fire missions army field ArtillerySafety T fire missions army field Artillery
Safety T fire missions army field Artillery
 
The Psychology Of Motivation - Richard Brown
The Psychology Of Motivation - Richard BrownThe Psychology Of Motivation - Richard Brown
The Psychology Of Motivation - Richard Brown
 
Leaders enhance communication by actively listening, providing constructive f...
Leaders enhance communication by actively listening, providing constructive f...Leaders enhance communication by actively listening, providing constructive f...
Leaders enhance communication by actively listening, providing constructive f...
 
Dealing with Poor Performance - get the full picture from 3C Performance Mana...
Dealing with Poor Performance - get the full picture from 3C Performance Mana...Dealing with Poor Performance - get the full picture from 3C Performance Mana...
Dealing with Poor Performance - get the full picture from 3C Performance Mana...
 
Abortion pills in Jeddah |• +966572737505 ] GET CYTOTEC
Abortion pills in Jeddah |• +966572737505 ] GET CYTOTECAbortion pills in Jeddah |• +966572737505 ] GET CYTOTEC
Abortion pills in Jeddah |• +966572737505 ] GET CYTOTEC
 
Strategic Management, Vision Mission, Internal Analsysis
Strategic Management, Vision Mission, Internal AnalsysisStrategic Management, Vision Mission, Internal Analsysis
Strategic Management, Vision Mission, Internal Analsysis
 
How Software Developers Destroy Business Value.pptx
How Software Developers Destroy Business Value.pptxHow Software Developers Destroy Business Value.pptx
How Software Developers Destroy Business Value.pptx
 
W.H.Bender Quote 62 - Always strive to be a Hospitality Service professional
W.H.Bender Quote 62 - Always strive to be a Hospitality Service professionalW.H.Bender Quote 62 - Always strive to be a Hospitality Service professional
W.H.Bender Quote 62 - Always strive to be a Hospitality Service professional
 
Independent Escorts Vikaspuri / 9899900591 High Profile Escort Service in Delhi
Independent Escorts Vikaspuri  / 9899900591 High Profile Escort Service in DelhiIndependent Escorts Vikaspuri  / 9899900591 High Profile Escort Service in Delhi
Independent Escorts Vikaspuri / 9899900591 High Profile Escort Service in Delhi
 
International Ocean Transportation p.pdf
International Ocean Transportation p.pdfInternational Ocean Transportation p.pdf
International Ocean Transportation p.pdf
 
digital Human resource management presentation.pdf
digital Human resource management presentation.pdfdigital Human resource management presentation.pdf
digital Human resource management presentation.pdf
 
Agile Coaching Change Management Framework.pptx
Agile Coaching Change Management Framework.pptxAgile Coaching Change Management Framework.pptx
Agile Coaching Change Management Framework.pptx
 

Queue

  • 2. Queue Overview • Queue ADT • Basic operations of queue – Push (or Enqueue), Pop (or Dequeue) etc. • Implementations of queue using – array – linked list
  • 3. Queue • How to include a new person/item? • How to remove a particular person/item?
  • 4. Queue • Collection of items into which items may be added from rear end and from which items may be removed from the front end
  • 5. The Queue ADT • Fundamental operations: – Enqueue: Equivalent to an insert – Dequeue: Deletes the element from rear end – isEmpty: Returns true if there are no elements in the queue – ReadFront: Examines the element at the front of the queue – ReadRear: Examines the elements at the rear of the queue
  • 7. Queue ADT Specification Structure: Elements are added to one end and removed from the other end. Definitions: (Provided by user): MAX_ITEMS: Maximum number of items that might be on the queue. Item Type: Data type of the items on the queue. Operations: (Provided by the ADT): MakeEmpty Functions: Sets queue to an empty state. Preconditions: None PostCondition: Queue is empty. Boolean IsEmpty Functions: Determine whether the queue is empty. Preconditions: Queue has been initialized. PostCondition: Function value = (queue is empty) Boolean IsFull Functions: Determine whether the queue is full. Preconditions: Queue has been initialized. PostCondition: Function value = (queue is full) Enqueue (ItemType newItem) Functions: Add newItem at the rear of the queue. Preconditions: Queue has been initialized and is not full. PostCondition: newItem at the rear of the queue. Dequeue (ItemType& item) Functions: Remove tem from front of queue and returns it in item. Preconditions: Queue has been initialized and is not empty. PostCondition: The element at front has been removed from the queue. Item is copy of removed element.
  • 8. Queue ADT • Queue is known as FIFO (First In, First Out) lists. – The last element inserted will be the last to be retrieved
  • 9. Implementation of Queue • Any list implementation could be used to implement a queue – Arrays (static: the size of queue is given initially) – Linked lists (dynamic: never become full, except when memory overflows) • We will explore implementations based on array and linked list • Let’s see how to use an array to implement a queue first
  • 10. Array Implementation • Need to declare an array size ahead of time • Associated with each queue are front and rear – for an empty queue, set front and rear to -1 • enqueue (X) – (1) Increment front by 1 if front = -1 – (2) Increment rear by 1 – (3) Set queue[rear] = X • dequeue – (1) Delete value to queue[front] – (2) Increment front by 1 • These operations are performed in constant time?
  • 11. Queue class • Attributes of Queue – capacity: the max size of queue – rear: the index of the last element of queue – front: the index of the first element of queue – values: point to an array which stores elements of queue • Operations of Queue – IsEmpty: return true if queue is empty, return false otherwise – isFull: return true if queue is full, return false otherwise – readFront: return the element at the front of queue – readRear: return the element at the rear of queue – enqueue: add an element to the rear of queue – dequeue: delete the element from the front of queue – displayQueue: print all the data in the queue
  • 12. Implementing a Queue Class • Define data members: consider storage structure(s) • Attempt #1: Use an array with the rear and front equal to -1 e.g., Enqueue 75, Enqueue 89, Enqueue 64, … front rear 75 89 64 [0] [1] [2] [3] [4] • … Dequeue front rear 89 64 [0] [1] [2] [3] [4] front rear 89 64 [0] [1] [2] [3] [4] Dequeue (1) Delete queue[front] (2) Increment front by 1
  • 13. Problem? front rear 89 64 [0] [1] [2] [3] [4] OR front rear 89 64 [0] [1] [2] [3] [4] Dequeue ?????? (1) Delete value of queue[front] (2) Increment front by 1?????
  • 14. Queue class class Queue { public: Queue(int size = 10); // constructor ~Queue() { delete [] values; } // destructor bool isEmpty() { return rear == -1; } bool isFull() { return (rear-front) == maxRear; } double readFront(); double readRear(); void enqueue(double x); void dequeue(); void displayQueue(); private: int maxRear; // maxRear = capacity - 1 int rear; // index of currently inserted value int front; // index of next element to be deleted double [] values; // element array };
  • 15. Create Queue • The constructor of Queue – Allocate an array of size. By default, size = 10. – When the queue is full, rear will have its maximum value, i.e. capacity – 1. – Initially rear is set to -1. It means the queue is empty. Queue::Queue(int capacity /*= 10*/) { if(capacity<1) { cout<<“cannot create queue of size below 1”; return; } maxRear= capacity - 1; values = new double[capacity]; front = rear = -1; } Although the constructor dynamically allocates the queue array, the queue is still static. The size is fixed after the initialization.
  • 16. Enqueue • void Enqueue(double x); – Add an element to the queue – If the queue is full, print the error information. – Note rear always represents the index of the recently added element. Before adding an element, increment rear. void Queue::enqueue(const double x) { if (IsFull()) cout << "Error: the queue is full." << endl; else values[++rear] = x; //is it correct? }
  • 17. Dequeue • double dequeue() – Removes and return the element at the front of the queue – If the queue is empty, print the error information. (In this case, the return value is useless.) – Don’t forgot to shift all elements to left and modify rear void Queue::dequeue() { if (IsEmpty()) { cout << "Error: the queue is empty." << endl; return; } else { shiftElementsLeft(); //rear??? } }
  • 18. Queue Rear • double readRear() – Return the element at rear of the queue – Unlike dequeue, this function does not remove the element double Queue::readRear() { if (IsEmpty()) { cout << "Error: the queue is empty." << endl; return -1; } else return values[rear]; }
  • 19. Queue Front • double readFront() – Return the element at front of the queue – Unlike dequeue, this function does not remove the element double Queue::readFront() { if (IsEmpty()) { cout << "Error: the queue is empty." << endl; return -1; } else return values[front]; }
  • 20. Using Queue int main(void) { Queue q(5); q.enqueue(5.0); q.enqueue(6.5); q.enqueue(-3.0); q.enqueue(-8.0); q.displayQueue(); cout << “Front: " << q.getFront() << endl; cout << “Rear: " << q.getRear() << endl; q.dequeue(); cout << “Rear: " << q.getRear() << endl; cout << “Front: " << q.getFront() << endl; while (!q.isEmpty()) q.dequeue(); q.displayQueue(); return 0; } Result????
  • 22. Circular Queue • enqueue(X)? • dequeue()? • isEmpty()? • isFull()? • Constructor? • readFront()? • readRear()?
  • 23. Circular Queue • Enqueue(X)?rear = (rear+1)%capacity; values[rear]=x; • Dequeue()?if (!isEmpty()){front = (front+1)%capacity; return values[front]} • isEmpty()? return front == rear; • isFull()? return ((rear+1)%capacity) == front; • Constructor? set front = rear = 0 • readFront()?  if (!isEmpty()){return values[(front+1)%capacity];} • readRear()?  if (!isEmpty()){return values[rear];}
  • 24. Circular Queue • Alternate implementation? • Any modification in Queue class? – elementCount or currentSize??
  • 25. References • Data Structures and Algorithms, LUMS