SlideShare a Scribd company logo
Queue Data Structure
What is queue? A queue is a linier data structure. The concept is quite similar with stack. additions are made at the end or tail of the queue while removals are made from the front or head of the queue.  Access system a queue is referred to a FIFO structure (First-In First-Out)
Queue operations Add : adds a new node Add(X,Q)    add the value X to the tail of queue Remove : removes a node Remove(Q)    removes the head node and returns its value IsEmpty : reports whether the queue is empty IsEmpty(Q)    report whether the queue Q is empty IsFull : reports whether the queue is full IsFull(Q)    report whether the queue Q is full  Initialize : creates/initializes the queue Initialize(Q)    create a new empty queue named Q Destroy : deletes the contents of the queue (may be implemented by re-initializing the queue) Destroy(Q)    deletes the contents of the queue Q
Illustration/example Operation Queue’s contents Return value 1. Initialiaze(S) <empty> - 2. Add(A,Q) A - 3. Add(B,Q) A  B  - 4. Add(C,Q) A  B  C - 5. Remove(Q) B  C A 6. Add(D,Q) B  C  D - 7. Remove(Q) C  D B 8. Remove(Q) D C 9. Remove(Q) <empty> D
Exercise: Queue Operation What would the contents of a queue be after the following operations? Initialise(Q) Add(A,Q) Add(F,Q) Add(X,Q) Remove(Q) Add(B,Q) Remove(Q) Remove(Q)    B
Storing a queue in a static data structure This implementation stores the queue in an array.  The array indices at which the head and tail of the queue are currently stored must be maintained.  The head of the queue is not necessarily at index 0. The array can be a “circular array” – the queue “wraps round” if the last index of the array is reached. Example – storing a queue in an array of length 5
Storing a queue in a static data structure (2) Continue the above example to show the state of the queue after the following operations: Add(E,Q) Remove(Q) Add(W,Q) Add(J,Q) Add(K,Q) What happens at the last of these steps?
Storing a queue in a dynamic data structure Each node in a dynamic data structure contains data AND a reference to the next node. A queue also needs a reference to the head node AND a reference to the tail node. The following diagram describes the storage of a queue called Queue. Each node consists of data (DataItem) and a reference (NextNode). The first node is accessed using the name  Queue.Head . Its data is accessed using  Queue.Head.DataItem The second node is accessed using  Queue.Head.NextNode The last node is accessed using  Queue.Tail
Adding a node (Add) in a dynamic data structure The new node is to be added at the tail of the queue. The reference  Queue.Tail  should point to the new node, and the  NextNode  reference of the node previously at the tail of the queue should point to the  DataItem  of the new node.
Removing a node (Remove) in a dynamic data structure The value of  Queue.Head.DataItem  is returned. A temporary reference Temp is declared and set to point to head node in the queue (Temp =  Queue.Head ).  Queue.Head  is then set to point to the second node instead of the top node. The only reference to the original head node is now Temp and the memory used by this node can then be freed.
Queue Implementation
Queue Implementation in Java The Java Collections Framework in the most recent version of Java now includes queue classes.  As you did for the stack, you will create your own Queue class in order to learn how a queue is implemented.  Your class will again be a bit simpler than the Collections Framework one but it will do essentially the same job
The Queue Class Since you implemented your stack as a static structure, you will learn how to implement a dynamic structure for your Queue The nodes of the queue will represented by instances of a class  Node . This holds a data item of type  Object , and a reference to the next Node. The data item can contain  any kind of Java object . The  Queue  class has references to two Nodes, the head and the tail. The  constructor  sets these references to be null as there are no Nodes initially. The Queue does not have a fixed size, so it will never be full (unless the computer runs out of memory). The isFull method simple returns false here.
The Queue Class (2) Node.Java /* class Node.*/ public class Node { Object dataItem; Node nextNode; } Queue.Java /* class Queue */ public class Queue { public Node head; public Node tail; } /* Constructor for objects of class Queue */ public Queue() { // initialise head and tail references head = null; tail = null; } /* sets all queue entries to null */ public void destroy() { Node temp = new Node(); Node setNull = new Node(); temp = head; while (temp!=null) { setNull = temp; temp = temp.nextNode; setNull = null; } head = null; tail = null; }
The Queue Class (3) /* checks whether queue is empty*/ public boolean isEmpty() { return head == null; } /* add an item to the queue */ public void add(Object o) { Node newNode = new Node(); newNode.dataItem = o; if (tail == null) { head = newNode; tail = newNode; } else { tail.nextNode = newNode; tail = newNode; } } /* checks whether queue is full –  not properly implemented here */ public boolean isFull() { return false; } /* remove an item by obeying FIFO rule */ public Object remove() { if (head == null) return null; else { Node temp = new Node(); temp = head; head = head.nextNode; if (head == null) tail = null; return temp.dataItem; } }
The Queue Class (4) /* returns the number of items in the queue */ public int size() { int count = 0; for (Node current=head;current!=null; current=current.nextNode) count++; return count; }
Using a Queue To use the Queue class, you need to know how to write code to call the Queue operations, for example to add data to the Queue. Remember that the Queue can hold any kind of data. The following test class shows how to use a Queue to hold String objects.  /** / /*class QueueTester.  */ public class QueueTester { private Queue queue; public QueueTester(){ queue = new Queue(); } public QueueTester(Queue queue){ this.queue = queue; } } void addString(String str) void removeString() void checkIfEmpty() void listStringsInQueue()
Using a Queue (2) /* add item to queue */ public void addString(String str) { queue.add(str); System.out.println(&quot;Added new string&quot;); } /* remove item from queue */ public void removeString() { String result = (String) queue.remove(); if (result!=null) System.out.println(&quot;String is :&quot; + result); else System.out.println(&quot;Remove was unsuccessful&quot;); } /* check if queue is empty */ public void checkIfEmpty() { if (queue.isEmpty()) System.out.println(&quot;Queue empty&quot;); else System.out.println(&quot;Queue is not empty&quot;); } /* list the strings in queue */ public void listStringsInQueue() { if (queue.isEmpty()) { System.out.println(&quot;Queue empty&quot;); } else { System.out.println(&quot;Strings in queue are: &quot;); System.out.println(); Node node = queue.head; while (node != null){ String item = (String)node.dataItem; System.out.println(item); node = node.nextNode; } System.out.println(); } }
Exercise: Using a Queue Create a new BlueJ project called queues and create new classes Node, Queue and QueueTester using the above code. Create a new instance of Queue. Create a new instance of QueueTester and select your Queue instance in the object bench as the parameter in the constructor. This means that you will be testing the Queue you created in the previous step. Call the  checkIfEmpty  method of your  QueueTester . What was the result? Call the  addString  method of your  QueueTester  to add the string “The” to the queque. Repeat this to add the following strings: “queue”, “gets”, “longer” What result would you expect if you remove from the Queue? Call the  removeString  method of your  QueueTester  and check that you got the correct result. Call the  add  method of your  QueueTester  to add the strings “every” and “day” to the queue. What do you expect the contents of the Queue to be now? Inspect your Queue object. You should see references to the head and tail of the Queue.
For Your EXERCISE:  Storing other types of data Modify the QueueTester class to store Double objects in a Queue instead of String objects, and test in a similar way to the above. You should not have to change the Queue class at all.
EXERCISE: A practical application of the Queue class A queue is a useful data structure for holding data which should be processed in the order it is created, but which cannot always be processed straight away. A typical application might be a messaging system. In the following example, messages are received in the order they were sent. The classes involved are Message, MessageSender and MessageReceiver: A Message object has a sender, a recipient, a content string and a date. A Message is placed in a Queue by a MessageSender object. A Message is removed from the queue by a MessageReceiver object, which can also display the contents of the Queue. The Queue class you have created in this chapter can hold  any type of object , including Messages, so you can use it in this example as it is. Add the following classes to your queues project:
EXERCISE: A practical application (the code) Message.Java import java.text.*; import java.util.Date; /** class Message */ public class Message { public String sender; public String recipient; public String content; public Date date; /**Constructors for objects of class Message */ public Message() { this.sender = &quot;unknown sender&quot;; this.recipient = &quot;unknown recipient&quot;; this.content = &quot;none&quot;; this.date = new Date(); } public Message(String sender, String recipient, String content) { this.sender = sender; this.recipient = recipient; this.content = content; this.date = new Date(); } /**returns date/time at which message was created    * @return String - formatted representation of date */ public String getDate() { returnDateFormat.getDateTimeInstance(). format(this.date); } }
EXERCISE: A practical application (the code) MessageSender.Java /**class MessageSender. */ public class MessageSender { /** places a message on a specified queue */ public void sendMessage(String sender, String recipient, String content, Queue q) { Message m = new Message(sender, recipient, content); if(!q.isFull()){ q.add(m); System.out.println(&quot;Message placed on queue&quot;); } else System.out.println(&quot;Cannot send - queue is full&quot;); } }
EXERCISE: A practical application (the code) MessageReceiver.Java /** class MessageReceiver  */ public class MessageReceiver { /** receives and outputs a message from a specified queue */ public void receiveMessage(Queue q) { Message m = (Message) q.remove(); if (m != null) { System.out.println(&quot;Date: &quot; + m.getDate()); System.out.println(&quot;From: &quot; + m.sender); System.out.println(&quot;To: &quot; + m.recipient); System.out.println(&quot;Content: &quot; + m.content); } else System.out.println(&quot;No messages to receive&quot;); } /** outputs contents of a queue */ public void showQueue(Queue q) { Message m; System.out.println(&quot;Queue contains &quot; + q.size() + &quot; messages&quot;); if (q.isEmpty()) { System.out.println(&quot;Queue empty&quot;); } else { Node node = q.head; while (node != null){ m = (Message)node.dataItem; System.out.println(m.getDate() + &quot;, From:&quot; + m.sender + &quot;, To:&quot; + m.recipient); node = node.nextNode; } } } }
EXERCISE: A practical application of the Queue class (test sequence) Create new instances of MessageSender, MessageReceiver and your Queue class Use the MessageSender instance to add the following messages to the queue: Sender   Recipient   Content Rudy  Aini  Assalamu’alaikum Rida  Ahmad  What does the mean? Hakiem Husein  See you later Use the MessageReceiver instance to: Display the queue contents Remove the first message in the queue Display the queue contents again Use appropriate methods to add the following messages to the Queue, remove the first message and display the queue contents again. Sender   Recipient   Content Wildan  Abdul  Good Evening Diana  Fikri  Bye for now Use appropriate methods to remove the first message and add the following message to the Queue, and display the Queue contents again. Sender  Recipient  Content Rizki   Adinda  I love you
Ad

More Related Content

What's hot (20)

Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
Apurbo Datta
 
Stack & Queue using Linked List in Data Structure
Stack & Queue using Linked List in Data StructureStack & Queue using Linked List in Data Structure
Stack & Queue using Linked List in Data Structure
Meghaj Mallick
 
Queue
QueueQueue
Queue
Nabeel Ahsen
 
Hashing Technique In Data Structures
Hashing Technique In Data StructuresHashing Technique In Data Structures
Hashing Technique In Data Structures
SHAKOOR AB
 
Stack and Queue by M.Gomathi Lecturer
Stack and Queue by M.Gomathi LecturerStack and Queue by M.Gomathi Lecturer
Stack and Queue by M.Gomathi Lecturer
gomathi chlm
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
Abdullah Al-hazmy
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
Lovely Professional University
 
Stack
StackStack
Stack
Zaid Shabbir
 
Tree and Binary Search tree
Tree and Binary Search treeTree and Binary Search tree
Tree and Binary Search tree
Muhazzab Chouhadry
 
queue & its applications
queue & its applicationsqueue & its applications
queue & its applications
somendra kumar
 
Data structure by Digvijay
Data structure by DigvijayData structure by Digvijay
Data structure by Digvijay
Digvijay Singh Karakoti
 
Merge sort algorithm
Merge sort algorithmMerge sort algorithm
Merge sort algorithm
Shubham Dwivedi
 
Sets in python
Sets in pythonSets in python
Sets in python
baabtra.com - No. 1 supplier of quality freshers
 
Queue as data_structure
Queue as data_structureQueue as data_structure
Queue as data_structure
eShikshak
 
Queues
QueuesQueues
Queues
Hareem Aslam
 
Applications of stack
Applications of stackApplications of stack
Applications of stack
eShikshak
 
Binary search tree
Binary search treeBinary search tree
Binary search tree
Kousalya M
 
Stack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADTStack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADT
Soumen Santra
 
Linked List
Linked ListLinked List
Linked List
Ashim Lamichhane
 
Stack Data Structure & It's Application
Stack Data Structure & It's Application Stack Data Structure & It's Application
Stack Data Structure & It's Application
Tech_MX
 

Similar to Queue Data Structure (20)

queueDATA STRUCTURES AND ITS OPERATIONS IMPLEMETED WITH EXAMPLES
queueDATA STRUCTURES  AND ITS OPERATIONS IMPLEMETED WITH EXAMPLESqueueDATA STRUCTURES  AND ITS OPERATIONS IMPLEMETED WITH EXAMPLES
queueDATA STRUCTURES AND ITS OPERATIONS IMPLEMETED WITH EXAMPLES
KusumaS36
 
The presention is about the queue data structure
The presention is about the queue data structureThe presention is about the queue data structure
The presention is about the queue data structure
gaurav77712
 
LectureNotes-06-DSA
LectureNotes-06-DSALectureNotes-06-DSA
LectureNotes-06-DSA
Haitham El-Ghareeb
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
RAtna29
 
Lec2
Lec2Lec2
Lec2
Anjneya Varshney
 
Tutorial 6 queues & arrays & results recording
Tutorial 6   queues & arrays & results recording Tutorial 6   queues & arrays & results recording
Tutorial 6 queues & arrays & results recording
Mohd Batati
 
Mcq 15-20Q15Which of the following trees are binary search tr
Mcq 15-20Q15Which of the following trees are binary search trMcq 15-20Q15Which of the following trees are binary search tr
Mcq 15-20Q15Which of the following trees are binary search tr
AbramMartino96
 
Data structures and algorithms lab4
Data structures and algorithms lab4Data structures and algorithms lab4
Data structures and algorithms lab4
Bianca Teşilă
 
stack.ppt
stack.pptstack.ppt
stack.ppt
ssuserec1395
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
info309708
 
An Introduction to Stack Data Structures
An Introduction to Stack Data StructuresAn Introduction to Stack Data Structures
An Introduction to Stack Data Structures
berggold2024
 
introduction stacks in data structures and algorithms
introduction stacks in data structures and algorithmsintroduction stacks in data structures and algorithms
introduction stacks in data structures and algorithms
sneham64878
 
01-intro_stacks.ppt
01-intro_stacks.ppt01-intro_stacks.ppt
01-intro_stacks.ppt
soniya555961
 
2 b queues
2 b queues2 b queues
2 b queues
Nguync91368
 
Lec2
Lec2Lec2
Lec2
Nikhil Chilwant
 
Java Generics
Java GenericsJava Generics
Java Generics
jeslie
 
Sorted number list implementation with linked listsStep 1 Inspec.pdf
 Sorted number list implementation with linked listsStep 1 Inspec.pdf Sorted number list implementation with linked listsStep 1 Inspec.pdf
Sorted number list implementation with linked listsStep 1 Inspec.pdf
almaniaeyewear
 
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docxIn Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
bradburgess22840
 
Stack linked list
Stack linked listStack linked list
Stack linked list
bhargav0077
 
Using NetBeansImplement a queue named QueueLL using a Linked List .pdf
Using NetBeansImplement a queue named QueueLL using a Linked List .pdfUsing NetBeansImplement a queue named QueueLL using a Linked List .pdf
Using NetBeansImplement a queue named QueueLL using a Linked List .pdf
siennatimbok52331
 
queueDATA STRUCTURES AND ITS OPERATIONS IMPLEMETED WITH EXAMPLES
queueDATA STRUCTURES  AND ITS OPERATIONS IMPLEMETED WITH EXAMPLESqueueDATA STRUCTURES  AND ITS OPERATIONS IMPLEMETED WITH EXAMPLES
queueDATA STRUCTURES AND ITS OPERATIONS IMPLEMETED WITH EXAMPLES
KusumaS36
 
The presention is about the queue data structure
The presention is about the queue data structureThe presention is about the queue data structure
The presention is about the queue data structure
gaurav77712
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
RAtna29
 
Tutorial 6 queues & arrays & results recording
Tutorial 6   queues & arrays & results recording Tutorial 6   queues & arrays & results recording
Tutorial 6 queues & arrays & results recording
Mohd Batati
 
Mcq 15-20Q15Which of the following trees are binary search tr
Mcq 15-20Q15Which of the following trees are binary search trMcq 15-20Q15Which of the following trees are binary search tr
Mcq 15-20Q15Which of the following trees are binary search tr
AbramMartino96
 
Data structures and algorithms lab4
Data structures and algorithms lab4Data structures and algorithms lab4
Data structures and algorithms lab4
Bianca Teşilă
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
info309708
 
An Introduction to Stack Data Structures
An Introduction to Stack Data StructuresAn Introduction to Stack Data Structures
An Introduction to Stack Data Structures
berggold2024
 
introduction stacks in data structures and algorithms
introduction stacks in data structures and algorithmsintroduction stacks in data structures and algorithms
introduction stacks in data structures and algorithms
sneham64878
 
01-intro_stacks.ppt
01-intro_stacks.ppt01-intro_stacks.ppt
01-intro_stacks.ppt
soniya555961
 
Java Generics
Java GenericsJava Generics
Java Generics
jeslie
 
Sorted number list implementation with linked listsStep 1 Inspec.pdf
 Sorted number list implementation with linked listsStep 1 Inspec.pdf Sorted number list implementation with linked listsStep 1 Inspec.pdf
Sorted number list implementation with linked listsStep 1 Inspec.pdf
almaniaeyewear
 
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docxIn Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
bradburgess22840
 
Stack linked list
Stack linked listStack linked list
Stack linked list
bhargav0077
 
Using NetBeansImplement a queue named QueueLL using a Linked List .pdf
Using NetBeansImplement a queue named QueueLL using a Linked List .pdfUsing NetBeansImplement a queue named QueueLL using a Linked List .pdf
Using NetBeansImplement a queue named QueueLL using a Linked List .pdf
siennatimbok52331
 
Ad

More from Zidny Nafan (6)

Materi 4 Information System Engineering Sim 1223511116853894 8
Materi 4 Information System Engineering Sim 1223511116853894 8Materi 4 Information System Engineering Sim 1223511116853894 8
Materi 4 Information System Engineering Sim 1223511116853894 8
Zidny Nafan
 
Kuliah1 Struktur Data V1.0
Kuliah1 Struktur Data V1.0Kuliah1 Struktur Data V1.0
Kuliah1 Struktur Data V1.0
Zidny Nafan
 
Stack Implementation
Stack ImplementationStack Implementation
Stack Implementation
Zidny Nafan
 
Stack Data Structure V1.0
Stack Data Structure V1.0Stack Data Structure V1.0
Stack Data Structure V1.0
Zidny Nafan
 
List Data Structure
List Data StructureList Data Structure
List Data Structure
Zidny Nafan
 
Materi 4 Information System Engineering Sim 1223511116853894 8
Materi 4 Information System Engineering Sim 1223511116853894 8Materi 4 Information System Engineering Sim 1223511116853894 8
Materi 4 Information System Engineering Sim 1223511116853894 8
Zidny Nafan
 
Kuliah1 Struktur Data V1.0
Kuliah1 Struktur Data V1.0Kuliah1 Struktur Data V1.0
Kuliah1 Struktur Data V1.0
Zidny Nafan
 
Stack Implementation
Stack ImplementationStack Implementation
Stack Implementation
Zidny Nafan
 
Stack Data Structure V1.0
Stack Data Structure V1.0Stack Data Structure V1.0
Stack Data Structure V1.0
Zidny Nafan
 
List Data Structure
List Data StructureList Data Structure
List Data Structure
Zidny Nafan
 
Ad

Recently uploaded (20)

Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and GuestsLDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDM Mia eStudios
 
Module 1: Foundations of Research
Module 1: Foundations of ResearchModule 1: Foundations of Research
Module 1: Foundations of Research
drroxannekemp
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
Cultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptxCultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptx
UmeshTimilsina1
 
Cultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptxCultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptx
UmeshTimilsina1
 
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Leonel Morgado
 
Form View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo SlidesForm View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo Slides
Celine George
 
Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)
Mohamed Rizk Khodair
 
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Association for Project Management
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptxTERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
PoojaSen20
 
UPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guideUPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guide
abmerca
 
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFAMEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
Dr. Nasir Mustafa
 
Drugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdfDrugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdf
crewot855
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
parmarjuli1412
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and GuestsLDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDM Mia eStudios
 
Module 1: Foundations of Research
Module 1: Foundations of ResearchModule 1: Foundations of Research
Module 1: Foundations of Research
drroxannekemp
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
Cultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptxCultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptx
UmeshTimilsina1
 
Cultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptxCultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptx
UmeshTimilsina1
 
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Leonel Morgado
 
Form View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo SlidesForm View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo Slides
Celine George
 
Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)
Mohamed Rizk Khodair
 
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Association for Project Management
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptxTERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
PoojaSen20
 
UPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guideUPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guide
abmerca
 
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFAMEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
Dr. Nasir Mustafa
 
Drugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdfDrugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdf
crewot855
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
parmarjuli1412
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 

Queue Data Structure

  • 2. What is queue? A queue is a linier data structure. The concept is quite similar with stack. additions are made at the end or tail of the queue while removals are made from the front or head of the queue. Access system a queue is referred to a FIFO structure (First-In First-Out)
  • 3. Queue operations Add : adds a new node Add(X,Q)  add the value X to the tail of queue Remove : removes a node Remove(Q)  removes the head node and returns its value IsEmpty : reports whether the queue is empty IsEmpty(Q)  report whether the queue Q is empty IsFull : reports whether the queue is full IsFull(Q)  report whether the queue Q is full Initialize : creates/initializes the queue Initialize(Q)  create a new empty queue named Q Destroy : deletes the contents of the queue (may be implemented by re-initializing the queue) Destroy(Q)  deletes the contents of the queue Q
  • 4. Illustration/example Operation Queue’s contents Return value 1. Initialiaze(S) <empty> - 2. Add(A,Q) A - 3. Add(B,Q) A B - 4. Add(C,Q) A B C - 5. Remove(Q) B C A 6. Add(D,Q) B C D - 7. Remove(Q) C D B 8. Remove(Q) D C 9. Remove(Q) <empty> D
  • 5. Exercise: Queue Operation What would the contents of a queue be after the following operations? Initialise(Q) Add(A,Q) Add(F,Q) Add(X,Q) Remove(Q) Add(B,Q) Remove(Q) Remove(Q)  B
  • 6. Storing a queue in a static data structure This implementation stores the queue in an array. The array indices at which the head and tail of the queue are currently stored must be maintained. The head of the queue is not necessarily at index 0. The array can be a “circular array” – the queue “wraps round” if the last index of the array is reached. Example – storing a queue in an array of length 5
  • 7. Storing a queue in a static data structure (2) Continue the above example to show the state of the queue after the following operations: Add(E,Q) Remove(Q) Add(W,Q) Add(J,Q) Add(K,Q) What happens at the last of these steps?
  • 8. Storing a queue in a dynamic data structure Each node in a dynamic data structure contains data AND a reference to the next node. A queue also needs a reference to the head node AND a reference to the tail node. The following diagram describes the storage of a queue called Queue. Each node consists of data (DataItem) and a reference (NextNode). The first node is accessed using the name Queue.Head . Its data is accessed using Queue.Head.DataItem The second node is accessed using Queue.Head.NextNode The last node is accessed using Queue.Tail
  • 9. Adding a node (Add) in a dynamic data structure The new node is to be added at the tail of the queue. The reference Queue.Tail should point to the new node, and the NextNode reference of the node previously at the tail of the queue should point to the DataItem of the new node.
  • 10. Removing a node (Remove) in a dynamic data structure The value of Queue.Head.DataItem is returned. A temporary reference Temp is declared and set to point to head node in the queue (Temp = Queue.Head ). Queue.Head is then set to point to the second node instead of the top node. The only reference to the original head node is now Temp and the memory used by this node can then be freed.
  • 12. Queue Implementation in Java The Java Collections Framework in the most recent version of Java now includes queue classes. As you did for the stack, you will create your own Queue class in order to learn how a queue is implemented. Your class will again be a bit simpler than the Collections Framework one but it will do essentially the same job
  • 13. The Queue Class Since you implemented your stack as a static structure, you will learn how to implement a dynamic structure for your Queue The nodes of the queue will represented by instances of a class Node . This holds a data item of type Object , and a reference to the next Node. The data item can contain any kind of Java object . The Queue class has references to two Nodes, the head and the tail. The constructor sets these references to be null as there are no Nodes initially. The Queue does not have a fixed size, so it will never be full (unless the computer runs out of memory). The isFull method simple returns false here.
  • 14. The Queue Class (2) Node.Java /* class Node.*/ public class Node { Object dataItem; Node nextNode; } Queue.Java /* class Queue */ public class Queue { public Node head; public Node tail; } /* Constructor for objects of class Queue */ public Queue() { // initialise head and tail references head = null; tail = null; } /* sets all queue entries to null */ public void destroy() { Node temp = new Node(); Node setNull = new Node(); temp = head; while (temp!=null) { setNull = temp; temp = temp.nextNode; setNull = null; } head = null; tail = null; }
  • 15. The Queue Class (3) /* checks whether queue is empty*/ public boolean isEmpty() { return head == null; } /* add an item to the queue */ public void add(Object o) { Node newNode = new Node(); newNode.dataItem = o; if (tail == null) { head = newNode; tail = newNode; } else { tail.nextNode = newNode; tail = newNode; } } /* checks whether queue is full – not properly implemented here */ public boolean isFull() { return false; } /* remove an item by obeying FIFO rule */ public Object remove() { if (head == null) return null; else { Node temp = new Node(); temp = head; head = head.nextNode; if (head == null) tail = null; return temp.dataItem; } }
  • 16. The Queue Class (4) /* returns the number of items in the queue */ public int size() { int count = 0; for (Node current=head;current!=null; current=current.nextNode) count++; return count; }
  • 17. Using a Queue To use the Queue class, you need to know how to write code to call the Queue operations, for example to add data to the Queue. Remember that the Queue can hold any kind of data. The following test class shows how to use a Queue to hold String objects. /** / /*class QueueTester. */ public class QueueTester { private Queue queue; public QueueTester(){ queue = new Queue(); } public QueueTester(Queue queue){ this.queue = queue; } } void addString(String str) void removeString() void checkIfEmpty() void listStringsInQueue()
  • 18. Using a Queue (2) /* add item to queue */ public void addString(String str) { queue.add(str); System.out.println(&quot;Added new string&quot;); } /* remove item from queue */ public void removeString() { String result = (String) queue.remove(); if (result!=null) System.out.println(&quot;String is :&quot; + result); else System.out.println(&quot;Remove was unsuccessful&quot;); } /* check if queue is empty */ public void checkIfEmpty() { if (queue.isEmpty()) System.out.println(&quot;Queue empty&quot;); else System.out.println(&quot;Queue is not empty&quot;); } /* list the strings in queue */ public void listStringsInQueue() { if (queue.isEmpty()) { System.out.println(&quot;Queue empty&quot;); } else { System.out.println(&quot;Strings in queue are: &quot;); System.out.println(); Node node = queue.head; while (node != null){ String item = (String)node.dataItem; System.out.println(item); node = node.nextNode; } System.out.println(); } }
  • 19. Exercise: Using a Queue Create a new BlueJ project called queues and create new classes Node, Queue and QueueTester using the above code. Create a new instance of Queue. Create a new instance of QueueTester and select your Queue instance in the object bench as the parameter in the constructor. This means that you will be testing the Queue you created in the previous step. Call the checkIfEmpty method of your QueueTester . What was the result? Call the addString method of your QueueTester to add the string “The” to the queque. Repeat this to add the following strings: “queue”, “gets”, “longer” What result would you expect if you remove from the Queue? Call the removeString method of your QueueTester and check that you got the correct result. Call the add method of your QueueTester to add the strings “every” and “day” to the queue. What do you expect the contents of the Queue to be now? Inspect your Queue object. You should see references to the head and tail of the Queue.
  • 20. For Your EXERCISE: Storing other types of data Modify the QueueTester class to store Double objects in a Queue instead of String objects, and test in a similar way to the above. You should not have to change the Queue class at all.
  • 21. EXERCISE: A practical application of the Queue class A queue is a useful data structure for holding data which should be processed in the order it is created, but which cannot always be processed straight away. A typical application might be a messaging system. In the following example, messages are received in the order they were sent. The classes involved are Message, MessageSender and MessageReceiver: A Message object has a sender, a recipient, a content string and a date. A Message is placed in a Queue by a MessageSender object. A Message is removed from the queue by a MessageReceiver object, which can also display the contents of the Queue. The Queue class you have created in this chapter can hold any type of object , including Messages, so you can use it in this example as it is. Add the following classes to your queues project:
  • 22. EXERCISE: A practical application (the code) Message.Java import java.text.*; import java.util.Date; /** class Message */ public class Message { public String sender; public String recipient; public String content; public Date date; /**Constructors for objects of class Message */ public Message() { this.sender = &quot;unknown sender&quot;; this.recipient = &quot;unknown recipient&quot;; this.content = &quot;none&quot;; this.date = new Date(); } public Message(String sender, String recipient, String content) { this.sender = sender; this.recipient = recipient; this.content = content; this.date = new Date(); } /**returns date/time at which message was created * @return String - formatted representation of date */ public String getDate() { returnDateFormat.getDateTimeInstance(). format(this.date); } }
  • 23. EXERCISE: A practical application (the code) MessageSender.Java /**class MessageSender. */ public class MessageSender { /** places a message on a specified queue */ public void sendMessage(String sender, String recipient, String content, Queue q) { Message m = new Message(sender, recipient, content); if(!q.isFull()){ q.add(m); System.out.println(&quot;Message placed on queue&quot;); } else System.out.println(&quot;Cannot send - queue is full&quot;); } }
  • 24. EXERCISE: A practical application (the code) MessageReceiver.Java /** class MessageReceiver */ public class MessageReceiver { /** receives and outputs a message from a specified queue */ public void receiveMessage(Queue q) { Message m = (Message) q.remove(); if (m != null) { System.out.println(&quot;Date: &quot; + m.getDate()); System.out.println(&quot;From: &quot; + m.sender); System.out.println(&quot;To: &quot; + m.recipient); System.out.println(&quot;Content: &quot; + m.content); } else System.out.println(&quot;No messages to receive&quot;); } /** outputs contents of a queue */ public void showQueue(Queue q) { Message m; System.out.println(&quot;Queue contains &quot; + q.size() + &quot; messages&quot;); if (q.isEmpty()) { System.out.println(&quot;Queue empty&quot;); } else { Node node = q.head; while (node != null){ m = (Message)node.dataItem; System.out.println(m.getDate() + &quot;, From:&quot; + m.sender + &quot;, To:&quot; + m.recipient); node = node.nextNode; } } } }
  • 25. EXERCISE: A practical application of the Queue class (test sequence) Create new instances of MessageSender, MessageReceiver and your Queue class Use the MessageSender instance to add the following messages to the queue: Sender Recipient Content Rudy Aini Assalamu’alaikum Rida Ahmad What does the mean? Hakiem Husein See you later Use the MessageReceiver instance to: Display the queue contents Remove the first message in the queue Display the queue contents again Use appropriate methods to add the following messages to the Queue, remove the first message and display the queue contents again. Sender Recipient Content Wildan Abdul Good Evening Diana Fikri Bye for now Use appropriate methods to remove the first message and add the following message to the Queue, and display the Queue contents again. Sender Recipient Content Rizki Adinda I love you
  翻译: