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

More Related Content

PPT
Queue Data Structure
PPT
Queue Data Structure
PPTX
Stack and Queue
PPTX
The presention is about the queue data structure
PPT
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
PPT
Lec-07 Queues.ppt queues introduction to queue
PPT
stack.ppt
Queue Data Structure
Queue Data Structure
Stack and Queue
The presention is about the queue data structure
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
Lec-07 Queues.ppt queues introduction to queue
stack.ppt

Similar to queueDATA STRUCTURES AND ITS OPERATIONS IMPLEMETED WITH EXAMPLES (20)

PPTX
Using-Python-Libraries.9485146.powerpoint.pptx
PPT
PDF
DSA Lab Manual C Scheme.pdf
PPTX
C++ STL (quickest way to learn, even for absolute beginners).pptx
PPTX
C++ STL (quickest way to learn, even for absolute beginners).pptx
PPT
basics of queues
PDF
LectureNotes-06-DSA
PPTX
Data Structures and Agorithm: DS 09 Queue.pptx
PDF
lecture6 Queue.pdfaonkjlasnknknlkasnncknckn
DOCX
Mcq 15-20Q15Which of the following trees are binary search tr
PPTX
Data structures
PPT
Stacks, Queues, Deques
PDF
Fjdkkdnncmckkgkhkhkkhkhkhkhkhkhkhkhkhkhhl
PPTX
PPT
2 b queues
PPTX
Bca ii dfs u-2 linklist,stack,queue
DOCX
DS UNIT5_BINARY TREES.docx
PPT
Data structures
PPT
Stack linked list
Using-Python-Libraries.9485146.powerpoint.pptx
DSA Lab Manual C Scheme.pdf
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
basics of queues
LectureNotes-06-DSA
Data Structures and Agorithm: DS 09 Queue.pptx
lecture6 Queue.pdfaonkjlasnknknlkasnncknckn
Mcq 15-20Q15Which of the following trees are binary search tr
Data structures
Stacks, Queues, Deques
Fjdkkdnncmckkgkhkhkkhkhkhkhkhkhkhkhkhkhhl
2 b queues
Bca ii dfs u-2 linklist,stack,queue
DS UNIT5_BINARY TREES.docx
Data structures
Stack linked list
Ad

Recently uploaded (20)

PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPTX
Sustainable Sites - Green Building Construction
PPTX
CH1 Production IntroductoryConcepts.pptx
PPTX
web development for engineering and engineering
PDF
Well-logging-methods_new................
PPTX
Safety Seminar civil to be ensured for safe working.
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PDF
composite construction of structures.pdf
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPTX
Current and future trends in Computer Vision.pptx
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPTX
bas. eng. economics group 4 presentation 1.pptx
PPTX
Construction Project Organization Group 2.pptx
PPT
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
Artificial Intelligence
Model Code of Practice - Construction Work - 21102022 .pdf
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
Sustainable Sites - Green Building Construction
CH1 Production IntroductoryConcepts.pptx
web development for engineering and engineering
Well-logging-methods_new................
Safety Seminar civil to be ensured for safe working.
Foundation to blockchain - A guide to Blockchain Tech
composite construction of structures.pdf
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
Current and future trends in Computer Vision.pptx
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
bas. eng. economics group 4 presentation 1.pptx
Construction Project Organization Group 2.pptx
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
OOP with Java - Java Introduction (Basics)
Artificial Intelligence
Ad

queueDATA STRUCTURES AND ITS OPERATIONS IMPLEMETED WITH EXAMPLES

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