SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances (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
 

Similaire à Queue

Similaire à 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
 

Plus de 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
 

Plus de 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
 

Dernier

internal analysis on strategic management
internal analysis on strategic managementinternal analysis on strategic management
internal analysis on strategic managementharfimakarim
 
VIP 7001035870 Find & Meet Hyderabad Call Girls Kondapur high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls Kondapur high-profile Call GirlVIP 7001035870 Find & Meet Hyderabad Call Girls Kondapur high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls Kondapur high-profile Call Girladitipandeya
 
GENUINE Babe,Call Girls IN Baderpur Delhi | +91-8377087607
GENUINE Babe,Call Girls IN Baderpur  Delhi | +91-8377087607GENUINE Babe,Call Girls IN Baderpur  Delhi | +91-8377087607
GENUINE Babe,Call Girls IN Baderpur Delhi | +91-8377087607dollysharma2066
 
operational plan ppt.pptx nursing management
operational plan ppt.pptx nursing managementoperational plan ppt.pptx nursing management
operational plan ppt.pptx nursing managementTulsiDhidhi1
 
Call now : 9892124323 Nalasopara Beautiful Call Girls Vasai virar Best Call G...
Call now : 9892124323 Nalasopara Beautiful Call Girls Vasai virar Best Call G...Call now : 9892124323 Nalasopara Beautiful Call Girls Vasai virar Best Call G...
Call now : 9892124323 Nalasopara Beautiful Call Girls Vasai virar Best Call G...Pooja Nehwal
 
VIP 7001035870 Find & Meet Hyderabad Call Girls Ameerpet high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls Ameerpet high-profile Call GirlVIP 7001035870 Find & Meet Hyderabad Call Girls Ameerpet high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls Ameerpet high-profile Call Girladitipandeya
 
VIP Kolkata Call Girl Rajarhat 👉 8250192130 Available With Room
VIP Kolkata Call Girl Rajarhat 👉 8250192130  Available With RoomVIP Kolkata Call Girl Rajarhat 👉 8250192130  Available With Room
VIP Kolkata Call Girl Rajarhat 👉 8250192130 Available With Roomdivyansh0kumar0
 
CEO of Google, Sunder Pichai's biography
CEO of Google, Sunder Pichai's biographyCEO of Google, Sunder Pichai's biography
CEO of Google, Sunder Pichai's biographyHafizMuhammadAbdulla5
 
Pooja Mehta 9167673311, Trusted Call Girls In NAVI MUMBAI Cash On Payment , V...
Pooja Mehta 9167673311, Trusted Call Girls In NAVI MUMBAI Cash On Payment , V...Pooja Mehta 9167673311, Trusted Call Girls In NAVI MUMBAI Cash On Payment , V...
Pooja Mehta 9167673311, Trusted Call Girls In NAVI MUMBAI Cash On Payment , V...Pooja Nehwal
 

Dernier (20)

Becoming an Inclusive Leader - Bernadette Thompson
Becoming an Inclusive Leader - Bernadette ThompsonBecoming an Inclusive Leader - Bernadette Thompson
Becoming an Inclusive Leader - Bernadette Thompson
 
Call Girls Service Tilak Nagar @9999965857 Delhi 🫦 No Advance VVIP 🍎 SERVICE
Call Girls Service Tilak Nagar @9999965857 Delhi 🫦 No Advance  VVIP 🍎 SERVICECall Girls Service Tilak Nagar @9999965857 Delhi 🫦 No Advance  VVIP 🍎 SERVICE
Call Girls Service Tilak Nagar @9999965857 Delhi 🫦 No Advance VVIP 🍎 SERVICE
 
internal analysis on strategic management
internal analysis on strategic managementinternal analysis on strategic management
internal analysis on strategic management
 
VIP 7001035870 Find & Meet Hyderabad Call Girls Kondapur high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls Kondapur high-profile Call GirlVIP 7001035870 Find & Meet Hyderabad Call Girls Kondapur high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls Kondapur high-profile Call Girl
 
GENUINE Babe,Call Girls IN Baderpur Delhi | +91-8377087607
GENUINE Babe,Call Girls IN Baderpur  Delhi | +91-8377087607GENUINE Babe,Call Girls IN Baderpur  Delhi | +91-8377087607
GENUINE Babe,Call Girls IN Baderpur Delhi | +91-8377087607
 
Disrupt or be Disrupted - Kirk Vallis.pdf
Disrupt or be Disrupted - Kirk Vallis.pdfDisrupt or be Disrupted - Kirk Vallis.pdf
Disrupt or be Disrupted - Kirk Vallis.pdf
 
operational plan ppt.pptx nursing management
operational plan ppt.pptx nursing managementoperational plan ppt.pptx nursing management
operational plan ppt.pptx nursing management
 
Peak Performance & Resilience - Dr Dorian Dugmore
Peak Performance & Resilience - Dr Dorian DugmorePeak Performance & Resilience - Dr Dorian Dugmore
Peak Performance & Resilience - Dr Dorian Dugmore
 
Rohini Sector 16 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 16 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 16 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 16 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
LoveLocalGov - Chris Twigg, Inner Circle
LoveLocalGov - Chris Twigg, Inner CircleLoveLocalGov - Chris Twigg, Inner Circle
LoveLocalGov - Chris Twigg, Inner Circle
 
Leadership in Crisis - Helio Vogas, Risk & Leadership Keynote Speaker
Leadership in Crisis - Helio Vogas, Risk & Leadership Keynote SpeakerLeadership in Crisis - Helio Vogas, Risk & Leadership Keynote Speaker
Leadership in Crisis - Helio Vogas, Risk & Leadership Keynote Speaker
 
Discover -CQ Master Class - Rikita Wadhwa.pdf
Discover -CQ Master Class - Rikita Wadhwa.pdfDiscover -CQ Master Class - Rikita Wadhwa.pdf
Discover -CQ Master Class - Rikita Wadhwa.pdf
 
Call now : 9892124323 Nalasopara Beautiful Call Girls Vasai virar Best Call G...
Call now : 9892124323 Nalasopara Beautiful Call Girls Vasai virar Best Call G...Call now : 9892124323 Nalasopara Beautiful Call Girls Vasai virar Best Call G...
Call now : 9892124323 Nalasopara Beautiful Call Girls Vasai virar Best Call G...
 
Empowering Local Government Frontline Services - Mo Baines.pdf
Empowering Local Government Frontline Services - Mo Baines.pdfEmpowering Local Government Frontline Services - Mo Baines.pdf
Empowering Local Government Frontline Services - Mo Baines.pdf
 
VIP 7001035870 Find & Meet Hyderabad Call Girls Ameerpet high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls Ameerpet high-profile Call GirlVIP 7001035870 Find & Meet Hyderabad Call Girls Ameerpet high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls Ameerpet high-profile Call Girl
 
VIP Kolkata Call Girl Rajarhat 👉 8250192130 Available With Room
VIP Kolkata Call Girl Rajarhat 👉 8250192130  Available With RoomVIP Kolkata Call Girl Rajarhat 👉 8250192130  Available With Room
VIP Kolkata Call Girl Rajarhat 👉 8250192130 Available With Room
 
CEO of Google, Sunder Pichai's biography
CEO of Google, Sunder Pichai's biographyCEO of Google, Sunder Pichai's biography
CEO of Google, Sunder Pichai's biography
 
Imagine - Creating Healthy Workplaces - Anthony Montgomery.pdf
Imagine - Creating Healthy Workplaces - Anthony Montgomery.pdfImagine - Creating Healthy Workplaces - Anthony Montgomery.pdf
Imagine - Creating Healthy Workplaces - Anthony Montgomery.pdf
 
Imagine - HR; are handling the 'bad banter' - Stella Chandler.pdf
Imagine - HR; are handling the 'bad banter' - Stella Chandler.pdfImagine - HR; are handling the 'bad banter' - Stella Chandler.pdf
Imagine - HR; are handling the 'bad banter' - Stella Chandler.pdf
 
Pooja Mehta 9167673311, Trusted Call Girls In NAVI MUMBAI Cash On Payment , V...
Pooja Mehta 9167673311, Trusted Call Girls In NAVI MUMBAI Cash On Payment , V...Pooja Mehta 9167673311, Trusted Call Girls In NAVI MUMBAI Cash On Payment , V...
Pooja Mehta 9167673311, Trusted Call Girls In NAVI MUMBAI Cash On Payment , V...
 

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