SlideShare a Scribd company logo
1 of 21
Implementing a Queue
as a Linked Structure
CS 308 – Data Structures
Implementing queues using
arrays
• Simple implementation
• The size of the queue must be determined
when a stack object is declared
• Space is wasted if we use less elements
• We cannot "enqueue" more elements than
the array can hold
Implementing queues using
linked lists
• Allocate memory for each new element
dynamically
• Link the queue elements together
• Use two pointers, qFront and qRear, to
mark the front and rear of the queue
Queue class specification
// forward declaration of NodeType (like function prototype)
template<class ItemType>
struct NodeType;
template<class ItemType>
class QueueType {
public:
QueueType();
~QueueType();
void MakeEmpty();
bool IsEmpty() const;
bool IsFull() const;
void Enqueue(ItemType);
void Dequeue(ItemType&);
private:
NodeType<ItemType>* qFront;
NodeType<ItemType>* qRear;
};
Enqueuing (non-empty queue)
Enqueuing (empty queue)
• We need to make qFront point to the new
node also
New Node
newNode
qFront = NULL
qRear = NULL
Function Enqueue
template <class ItemType>
void QueueType<ItemType>::Enqueue(ItemType
newItem)
{
NodeType<ItemType>* newNode;
newNode = new NodeType<ItemType>;
newNode->info = newItem;
newNode->next = NULL;
if(qRear == NULL)
qFront = newNode;
else
qRear->next = newNode;
qRear = newNode;
}
Dequeueing (the queue contains
more than one element)
Dequeueing (the queue contains
only one element)
• We need to reset qRear to NULL also
Node
qFront
qRear
After dequeue:
qFront = NULL
qRear = NULL
Function Dequeue
template <class ItemType>
void QueueType<ItemType>::Dequeue(ItemType& item)
{
NodeType<ItemType>* tempPtr;
tempPtr = qFront;
item = qFront->info;
qFront = qFront->next;
if(qFront == NULL)
qRear = NULL;
delete tempPtr;
}
qRear, qFront revisited
• The relative positions of qFront and qRear
are important!
Other Queue functions
template<class ItemType>
QueueType<ItemType>::QueueType()
{
qFront = NULL;
qRear = NULL;
}
template<class ItemType>
void QueueType<ItemType>::MakeEmpty()
{
NodeType<ItemType>* tempPtr;
while(qFront != NULL) {
tempPtr = qFront;
qFront = qFront->next;
delete tempPtr;
}
qRear=NULL;
}
Other Queue functions (cont.)
template<class ItemType>
bool QueueType<ItemType>::IsEmpty() const
{
return(qFront == NULL);
}
template<class ItemType>
bool QueueType<ItemType>::IsFull() const
{
NodeType<ItemType>* ptr;
ptr = new NodeType<ItemType>;
if(ptr == NULL)
return true;
else {
delete ptr;
return false;
}
}
Other Queue functions (cont.)
template<class ItemType>
QueueType<ItemType>::~QueueType()
{
MakeEmpty();
}
A circular linked queue design
Comparing queue implementations
• Memory requirements
– Array-based implementation
• Assume a queue (size: 100) of strings (80 bytes
each)
• Assume indices take 2 bytes
• Total memory: (80 bytes x 101 slots) + (2 bytes x 2
indexes) = 8084 bytes
– Linked-list-based implementation
• Assume pointers take 4 bytes
• Total memory per node: 80 bytes + 4 bytes = 84
bytes
Comparing
queue
implementations
(cont.)
Comparing queue implementations
• Memory requirements
– Array-based implementation
• Assume a queue (size: 100) of short integers
(2 bytes each)
• Assume indices take 2 bytes
• Total memory: (2 bytes x 101 slots) + (2 bytes x 2
indexes) = 206 bytes
– Linked-list-based implementation
• Assume pointers take 4 bytes
• Total memory per node: 2 bytes + 4 bytes = 6 bytes
(cont.)
Comparing
queue
implementations
(cont.)
Comparing queue implementations
Big-O Comparison of Queue Operations
Operation Array
Implementation
Linked
Implementation
Class constructor O(1) O(1)
MakeEmpty O(1) O(N)
IsFull O(1) O(1)
IsEmpty O(1) O(1)
Enqueue O(1) O(1)
Dequeue O(1) O(1)
Destructor O(1) O(N)
Exercises
• 5, 6

More Related Content

Similar to LinkedQueues.ppt

Ch03_stacks_and_queues.ppt
Ch03_stacks_and_queues.pptCh03_stacks_and_queues.ppt
Ch03_stacks_and_queues.pptOliverKane3
 
Fundamentals of Data Structure and Queues
Fundamentals of Data Structure and QueuesFundamentals of Data Structure and Queues
Fundamentals of Data Structure and QueuesBogiri Nagaraju
 
The Art of Java Type Patterns
The Art of Java Type PatternsThe Art of Java Type Patterns
The Art of Java Type PatternsSimon Ritter
 
2 BytesC++ course_2014_c13_ templates
2 BytesC++ course_2014_c13_ templates2 BytesC++ course_2014_c13_ templates
2 BytesC++ course_2014_c13_ templateskinan keshkeh
 
Writing native bindings to node.js in C++
Writing native bindings to node.js in C++Writing native bindings to node.js in C++
Writing native bindings to node.js in C++nsm.nikhil
 
I want help in the following C++ programming task. Please do coding .pdf
I want help in the following C++ programming task. Please do coding .pdfI want help in the following C++ programming task. Please do coding .pdf
I want help in the following C++ programming task. Please do coding .pdfbermanbeancolungak45
 
Create a Queue class that implements a queue abstraction. A queue is.docx
Create a Queue class that implements a queue abstraction. A queue is.docxCreate a Queue class that implements a queue abstraction. A queue is.docx
Create a Queue class that implements a queue abstraction. A queue is.docxrajahchelsey
 
Scala for Java Developers
Scala for Java DevelopersScala for Java Developers
Scala for Java DevelopersMartin Ockajak
 
Data Structures and Files
Data Structures and FilesData Structures and Files
Data Structures and FilesKanchanPatil34
 
Templates presentation
Templates presentationTemplates presentation
Templates presentationmalaybpramanik
 
Cocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magicCocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magicBadoo Development
 
Александр Зимин (Alexander Zimin) — Магия Swift
Александр Зимин (Alexander Zimin) — Магия SwiftАлександр Зимин (Alexander Zimin) — Магия Swift
Александр Зимин (Alexander Zimin) — Магия SwiftCocoaHeads
 
Robust C++ Task Systems Through Compile-time Checks
Robust C++ Task Systems Through Compile-time ChecksRobust C++ Task Systems Through Compile-time Checks
Robust C++ Task Systems Through Compile-time ChecksStoyan Nikolov
 

Similar to LinkedQueues.ppt (20)

Queue oop
Queue   oopQueue   oop
Queue oop
 
Ch03_stacks_and_queues.ppt
Ch03_stacks_and_queues.pptCh03_stacks_and_queues.ppt
Ch03_stacks_and_queues.ppt
 
Fundamentals of Data Structure and Queues
Fundamentals of Data Structure and QueuesFundamentals of Data Structure and Queues
Fundamentals of Data Structure and Queues
 
C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
 
The Art of Java Type Patterns
The Art of Java Type PatternsThe Art of Java Type Patterns
The Art of Java Type Patterns
 
Unit – iv queue
Unit – iv    queueUnit – iv    queue
Unit – iv queue
 
2 BytesC++ course_2014_c13_ templates
2 BytesC++ course_2014_c13_ templates2 BytesC++ course_2014_c13_ templates
2 BytesC++ course_2014_c13_ templates
 
Writing native bindings to node.js in C++
Writing native bindings to node.js in C++Writing native bindings to node.js in C++
Writing native bindings to node.js in C++
 
I want help in the following C++ programming task. Please do coding .pdf
I want help in the following C++ programming task. Please do coding .pdfI want help in the following C++ programming task. Please do coding .pdf
I want help in the following C++ programming task. Please do coding .pdf
 
Create a Queue class that implements a queue abstraction. A queue is.docx
Create a Queue class that implements a queue abstraction. A queue is.docxCreate a Queue class that implements a queue abstraction. A queue is.docx
Create a Queue class that implements a queue abstraction. A queue is.docx
 
Scala for Java Developers
Scala for Java DevelopersScala for Java Developers
Scala for Java Developers
 
Data Structures and Files
Data Structures and FilesData Structures and Files
Data Structures and Files
 
Queues.ppt
Queues.pptQueues.ppt
Queues.ppt
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
Cocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magicCocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magic
 
Александр Зимин (Alexander Zimin) — Магия Swift
Александр Зимин (Alexander Zimin) — Магия SwiftАлександр Зимин (Alexander Zimin) — Магия Swift
Александр Зимин (Alexander Zimin) — Магия Swift
 
Robust C++ Task Systems Through Compile-time Checks
Robust C++ Task Systems Through Compile-time ChecksRobust C++ Task Systems Through Compile-time Checks
Robust C++ Task Systems Through Compile-time Checks
 
Queues.ppt
Queues.pptQueues.ppt
Queues.ppt
 
Queues.ppt
Queues.pptQueues.ppt
Queues.ppt
 
Queues.ppt
Queues.pptQueues.ppt
Queues.ppt
 

More from LegesseSamuel

WachemoUniversity_Cryptography_and_Network_Security.pdf
WachemoUniversity_Cryptography_and_Network_Security.pdfWachemoUniversity_Cryptography_and_Network_Security.pdf
WachemoUniversity_Cryptography_and_Network_Security.pdfLegesseSamuel
 
DC Lecture 04 and 05 Mutual Excution and Election Algorithms.pdf
DC Lecture 04 and 05 Mutual Excution and Election Algorithms.pdfDC Lecture 04 and 05 Mutual Excution and Election Algorithms.pdf
DC Lecture 04 and 05 Mutual Excution and Election Algorithms.pdfLegesseSamuel
 
ADVANCED CALCULUS-SCHAUMSOUTLINE SERIES.pdf
ADVANCED CALCULUS-SCHAUMSOUTLINE SERIES.pdfADVANCED CALCULUS-SCHAUMSOUTLINE SERIES.pdf
ADVANCED CALCULUS-SCHAUMSOUTLINE SERIES.pdfLegesseSamuel
 
Advanced s and s algorithm.ppt
Advanced s and s algorithm.pptAdvanced s and s algorithm.ppt
Advanced s and s algorithm.pptLegesseSamuel
 
Computer Programming.pdf
Computer Programming.pdfComputer Programming.pdf
Computer Programming.pdfLegesseSamuel
 
Lect_4_Requirement Modeling(Use Case_and_Static).pdf
Lect_4_Requirement Modeling(Use Case_and_Static).pdfLect_4_Requirement Modeling(Use Case_and_Static).pdf
Lect_4_Requirement Modeling(Use Case_and_Static).pdfLegesseSamuel
 

More from LegesseSamuel (10)

WachemoUniversity_Cryptography_and_Network_Security.pdf
WachemoUniversity_Cryptography_and_Network_Security.pdfWachemoUniversity_Cryptography_and_Network_Security.pdf
WachemoUniversity_Cryptography_and_Network_Security.pdf
 
DC Lecture 04 and 05 Mutual Excution and Election Algorithms.pdf
DC Lecture 04 and 05 Mutual Excution and Election Algorithms.pdfDC Lecture 04 and 05 Mutual Excution and Election Algorithms.pdf
DC Lecture 04 and 05 Mutual Excution and Election Algorithms.pdf
 
ADVANCED CALCULUS-SCHAUMSOUTLINE SERIES.pdf
ADVANCED CALCULUS-SCHAUMSOUTLINE SERIES.pdfADVANCED CALCULUS-SCHAUMSOUTLINE SERIES.pdf
ADVANCED CALCULUS-SCHAUMSOUTLINE SERIES.pdf
 
ch20.ppt
ch20.pptch20.ppt
ch20.ppt
 
ch14.ppt
ch14.pptch14.ppt
ch14.ppt
 
ch11.ppt
ch11.pptch11.ppt
ch11.ppt
 
Advanced s and s algorithm.ppt
Advanced s and s algorithm.pptAdvanced s and s algorithm.ppt
Advanced s and s algorithm.ppt
 
Lecture-7.ppt
Lecture-7.pptLecture-7.ppt
Lecture-7.ppt
 
Computer Programming.pdf
Computer Programming.pdfComputer Programming.pdf
Computer Programming.pdf
 
Lect_4_Requirement Modeling(Use Case_and_Static).pdf
Lect_4_Requirement Modeling(Use Case_and_Static).pdfLect_4_Requirement Modeling(Use Case_and_Static).pdf
Lect_4_Requirement Modeling(Use Case_and_Static).pdf
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 

Recently uploaded (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 

LinkedQueues.ppt

  • 1. Implementing a Queue as a Linked Structure CS 308 – Data Structures
  • 2. Implementing queues using arrays • Simple implementation • The size of the queue must be determined when a stack object is declared • Space is wasted if we use less elements • We cannot "enqueue" more elements than the array can hold
  • 3. Implementing queues using linked lists • Allocate memory for each new element dynamically • Link the queue elements together • Use two pointers, qFront and qRear, to mark the front and rear of the queue
  • 4. Queue class specification // forward declaration of NodeType (like function prototype) template<class ItemType> struct NodeType; template<class ItemType> class QueueType { public: QueueType(); ~QueueType(); void MakeEmpty(); bool IsEmpty() const; bool IsFull() const; void Enqueue(ItemType); void Dequeue(ItemType&); private: NodeType<ItemType>* qFront; NodeType<ItemType>* qRear; };
  • 6. Enqueuing (empty queue) • We need to make qFront point to the new node also New Node newNode qFront = NULL qRear = NULL
  • 7. Function Enqueue template <class ItemType> void QueueType<ItemType>::Enqueue(ItemType newItem) { NodeType<ItemType>* newNode; newNode = new NodeType<ItemType>; newNode->info = newItem; newNode->next = NULL; if(qRear == NULL) qFront = newNode; else qRear->next = newNode; qRear = newNode; }
  • 8. Dequeueing (the queue contains more than one element)
  • 9. Dequeueing (the queue contains only one element) • We need to reset qRear to NULL also Node qFront qRear After dequeue: qFront = NULL qRear = NULL
  • 10. Function Dequeue template <class ItemType> void QueueType<ItemType>::Dequeue(ItemType& item) { NodeType<ItemType>* tempPtr; tempPtr = qFront; item = qFront->info; qFront = qFront->next; if(qFront == NULL) qRear = NULL; delete tempPtr; }
  • 11. qRear, qFront revisited • The relative positions of qFront and qRear are important!
  • 12. Other Queue functions template<class ItemType> QueueType<ItemType>::QueueType() { qFront = NULL; qRear = NULL; } template<class ItemType> void QueueType<ItemType>::MakeEmpty() { NodeType<ItemType>* tempPtr; while(qFront != NULL) { tempPtr = qFront; qFront = qFront->next; delete tempPtr; } qRear=NULL; }
  • 13. Other Queue functions (cont.) template<class ItemType> bool QueueType<ItemType>::IsEmpty() const { return(qFront == NULL); } template<class ItemType> bool QueueType<ItemType>::IsFull() const { NodeType<ItemType>* ptr; ptr = new NodeType<ItemType>; if(ptr == NULL) return true; else { delete ptr; return false; } }
  • 14. Other Queue functions (cont.) template<class ItemType> QueueType<ItemType>::~QueueType() { MakeEmpty(); }
  • 15. A circular linked queue design
  • 16. Comparing queue implementations • Memory requirements – Array-based implementation • Assume a queue (size: 100) of strings (80 bytes each) • Assume indices take 2 bytes • Total memory: (80 bytes x 101 slots) + (2 bytes x 2 indexes) = 8084 bytes – Linked-list-based implementation • Assume pointers take 4 bytes • Total memory per node: 80 bytes + 4 bytes = 84 bytes
  • 18. Comparing queue implementations • Memory requirements – Array-based implementation • Assume a queue (size: 100) of short integers (2 bytes each) • Assume indices take 2 bytes • Total memory: (2 bytes x 101 slots) + (2 bytes x 2 indexes) = 206 bytes – Linked-list-based implementation • Assume pointers take 4 bytes • Total memory per node: 2 bytes + 4 bytes = 6 bytes (cont.)
  • 20. Comparing queue implementations Big-O Comparison of Queue Operations Operation Array Implementation Linked Implementation Class constructor O(1) O(1) MakeEmpty O(1) O(N) IsFull O(1) O(1) IsEmpty O(1) O(1) Enqueue O(1) O(1) Dequeue O(1) O(1) Destructor O(1) O(N)