You are on page 1of 20

Republic of the Philippines

NUEVA VIZCAYA STATE UNIVERSITY


Bayombong, Nueva Vizcaya
INSTRUCTIONAL MODULE
IM No.:IM-IT ECC4-2NDSEM-2021-2022

COLLEGE OF ARTS AND SCIENCES


Bayombong Campus

DEGREE BSCS COURSE NO. IT ECC 4


PROGRAM
SPECIALIZATION Web Dev and Network COURSE Data Structure and Algorithm
Design and Management TITLE
YEAR LEVEL 1st Year TIME FRAME 5 WK 14-15 IM 07
hours NO. NO.

I. CHAPTER VII- QUEUE

II. LESSON TITLE


A. Anatomy of queue
B. Queue operation
C. Implementation of queue

III. LESSON OVERVIEW


This lesson will give the students a short knowledge on how to develop a program using the queue data
structure, to be familiar with the different operations and to illustrate the flow on how elements store and
retrieve in the data structure.

IV. DESIRED LEARNING OUTCOMES

At the end of the lesson, the student should be able to:

1. To declare a queue in C++ program.


2. To simulate actual structure of elements in the queue
4. To apply the concepts of queue in Java for (BSIT) and Python for (BSIS) program.

V. LESSON CONTENT

CHAPTER V: QUEUE DATA STRUCTURE

Introduction

You probably never thought that waiting in line in the supermarket would help you become a whiz at
data structures, but it’s a big help: the checkout line at a supermarket is similar to the way data structures are
organized. We’re the “things” organized by the supermarket line, and the same kind of organization is used for
data within your program. The checkout line in your program is called a queue.

At the end of this chapter, students must be able to:


 learn what is a queue;
 the difference simple queue vs. simple queue;
 identify the different operations in queue; and
 how to implement queue using array;

“In accordance with Section 185, Fair Use of Copyrighted Work of Republic Act 8293, the copyrighted works included in this material may be reproduced for educational
purposes only and not for commercial distribution,”
NVSU-FR-ICD-05-00 (081220) Page 1 of 20
Republic of the Philippines
NUEVA VIZCAYA STATE UNIVERSITY
Bayombong, Nueva Vizcaya
INSTRUCTIONAL MODULE
IM No.:IM-IT ECC4-2NDSEM-2021-2022

A. WHAT IS A QUEUE?

Queue is a list in data structure where insertion is done at one end (back or rear), while deletion is
performed at the other end (front).

Accessing the elements of queues by using the mechanism First In, First Out (FIFO) order.

For examples, is like customers standing in a check-out line in a store, the first customer in is the
first customer served.

B. A SIMPLE QUEUE VS. PRIORITY QUEUE

Simple Queue. It organizes items in a line where the first item is at the beginning of the line and the
last item is at the back of the line. Each item is processed in the order in which it appears in the queue.
The first item in line is processed first, followed by the second item and then the third until the last item
on the line is processed.

Priority Queue. This similar to a simple queue in that items are organized in a line and processed
sequentially. However, items on a priority queue can jump to the front of the line if they have priority.
Priority is a value that is associated with each item placed in the queue.
 The program processes the queue by scanning the queue for items with high priority.
 These are processed first regardless of their position in the line.
 All the other items are then processed sequentially after high priority items are processed.

C. Queue Implementation of Array

When an item is enqueued (inserted), the rear (back) index moves forward while when an item is
dequeued (deleted), the front index also moves forward by one element.

Illustrative Example:

Note: The problem here is that the rear index cannot move beyond the last element in the array.

“In accordance with Section 185, Fair Use of Copyrighted Work of Republic Act 8293, the copyrighted works included in this material may be reproduced for educational
purposes only and not for commercial distribution,”
NVSU-FR-ICD-05-00 (081220) Page 2 of 20
Republic of the Philippines
NUEVA VIZCAYA STATE UNIVERSITY
Bayombong, Nueva Vizcaya
INSTRUCTIONAL MODULE
IM No.:IM-IT ECC4-2NDSEM-2021-2022

D. THE ARRAY AND THE QUEUE


Data organized by a queue may be stored in an array. The queue determines the array element that is
at the front and back of the queue. So therefore, the array is not the queue likewise, the queue is not
the array.

Figure 7.1. The queue is different from the array used to store data
that appears in the queue.

E. OPERATIONS OF A QUEUE

1. Enqueue
– a value is placed in the back of the queue by performing the enqueue process, which consists
of two steps
o The first step is to identify the array element that is at the back of the queue. However, this
is not necessarily the last element of the array. Remember that the queue is not the array.
o the back of the queue is calculated by using the following formula:

back = (back+1) % size

Figure 7.2 shows how to use the formula and gives the values for the front, back, and size of the
queue. The front and back variables are set to zero because the queue is empty, and size is set to 8
because the array has 8 elements.

Figure 7.2. The enqueue process places a new value at the back of the queue.
Queue Overflow. A type error occurred when items are enqueue when the queue reaches
beyond its maximum capacity or size.

2. Dequeue. This is the process that removes a value from the front of the queue. It is important to
understand that the value is removed from the queue, not the array. The value always remains
“In accordance with Section 185, Fair Use of Copyrighted Work of Republic Act 8293, the copyrighted works included in this material may be reproduced for educational
purposes only and not for commercial distribution,”
NVSU-FR-ICD-05-00 (081220) Page 3 of 20
Republic of the Philippines
NUEVA VIZCAYA STATE UNIVERSITY
Bayombong, Nueva Vizcaya
INSTRUCTIONAL MODULE
IM No.:IM-IT ECC4-2NDSEM-2021-2022

assigned to the array until the value is either overwritten or the queue is abandoned. The front of
the queue is calculated by using the following formula:

front = (front+1) % 8

There are two steps in the dequeue process, as illustrated in Figure 3. The initial step is to calculate
the index of the array element at the front of the queue using the following expression:

Figure 7.3. The dequeue process removes an item from the front of a queue.

Notice that this expression is very similar to the expression used in the enqueue process to calculate
the index of the array element at the back of the queue.
 The first operation in this expression increments the value of the front variable. As you can see
in Figure 3, the front variable is assigned the initial value zero. Therefore, the result of the first
operation is 1.
 The next operation is to apply the modulus operator, which is identical to the modulus operation
performed in the enqueue process. The result of this operation is 1, meaning that the front of
the queue is the array element whose index is 1. This value is then assigned to the front
variable. Previously in this chapter, you learned that if you were at index 7 in the array, the
result of this calculation would be 0 ((7+1)%8 = 0), so you would chase the queue around in a
circle.
 The final step in the dequeue process is to use the value located at the front of the queue.
Typically, the dequeue process is a method, and the front of the queue is returned to the
statement that called the method.

Notice that the value 90 remains assigned to the values[1] array element in Figure 7.3 because values
assigned to the array associated with a queue are not affected when a value is removed from the front
of the queue. The queue keeps track of array elements that are at the front and back of the queue, not
the front or back of the array. In this case, we’re using a simple integer array to illustrate the principles
behind implementing the queue data structure. You may come across more complex implementations,
where each element in the array is a pointer to a class object or structure. In these cases, you should
be concerned about memory management when you perform enqueue and dequeue operations.

Queue Underflow. A type of an error occurred when items are dequeue from an empty queue

“In accordance with Section 185, Fair Use of Copyrighted Work of Republic Act 8293, the copyrighted works included in this material may be reproduced for educational
purposes only and not for commercial distribution,”
NVSU-FR-ICD-05-00 (081220) Page 4 of 20
Republic of the Philippines
NUEVA VIZCAYA STATE UNIVERSITY
Bayombong, Nueva Vizcaya
INSTRUCTIONAL MODULE
IM No.:IM-IT ECC4-2NDSEM-2021-2022

Queue
The Queue is used to insert elements at the end of the queue and removes from the beginning of the
queue. It follows FIFO concept. The Java Queue supports all methods of Collection interface including
insertion, deletion etc. LinkedList, ArrayBlockingQueue and PriorityQueue are the most frequently used
implementations.

The Java Queue interface, java.util.Queue represents a data structure designed to have elements inserted at
the end of the queue, and elements removed from the beginning of the queue. This is similar to how a queue in
a supermarket works.

The Java Queue interface is a subtype of the Java Collection interface. It represents an ordered sequence of
objects just like a Java List, but its intended use is slightly different. Because the Java Queue interface is a
subtype of the Java Collection interface, all methods in the Collection interface are also available in
the Queue interface.

Methods in Queue

Some of the commonly used methods of the Queue interface are:

 add() - Inserts the specified element into the queue. If the task is successful, add() returns true, if not it

throws an exception.
 offer() - Inserts the specified element into the queue. If the task is successful, offer() returns true, if not

it returns false.

 element() - Returns the head of the queue. Throws an exception if the queue is empty.

 peek() - Returns the head of the queue. Returns null if the queue is empty.

 remove() - Returns and removes the head of the queue. Throws an exception if the queue is empty.

 poll() - Returns and removes the head of the queue. Returns null if the queue is empty.

Implementation of the Queue Interface

1. Implementing the LinkedList Class

import java.util.Queue;
import java.util.LinkedList;

class Main {
“In accordance with Section 185, Fair Use of Copyrighted Work of Republic Act 8293, the copyrighted works included in this material may be reproduced for educational
purposes only and not for commercial distribution,”
NVSU-FR-ICD-05-00 (081220) Page 5 of 20
Republic of the Philippines
NUEVA VIZCAYA STATE UNIVERSITY
Bayombong, Nueva Vizcaya
INSTRUCTIONAL MODULE
IM No.:IM-IT ECC4-2NDSEM-2021-2022

public static void main(String[] args) {


// Creating Queue using the LinkedList class
Queue<Integer> numbers = new LinkedList<>();

// offer elements to the Queue


numbers.offer(1);
numbers.offer(2);
numbers.offer(3);
System.out.println("Queue: " + numbers);

// Access elements of the Queue


int accessedNumber = numbers.peek();
System.out.println("Accessed Element: " + accessedNumber);

// Remove elements from the Queue


int removedNumber = numbers.poll();
System.out.println("Removed Element: " + removedNumber);

System.out.println("Updated Queue: " + numbers);


}
}

Output

Queue: [1, 2, 3]
Accessed Element: 1
Removed Element: 1
Updated Queue: [2, 3]

To learn more, visit Java LinkedList.

2. Implementing the PriorityQueue Class

import java.util.Queue;
import java.util.PriorityQueue;

class Main {

public static void main(String[] args) {


// Creating Queue using the PriorityQueue class
Queue<Integer> numbers = new PriorityQueue<>();

// offer elements to the Queue


numbers.offer(5);
numbers.offer(1);
numbers.offer(2);
System.out.println("Queue: " + numbers);

“In accordance with Section 185, Fair Use of Copyrighted Work of Republic Act 8293, the copyrighted works included in this material may be reproduced for educational
purposes only and not for commercial distribution,”
NVSU-FR-ICD-05-00 (081220) Page 6 of 20
Republic of the Philippines
NUEVA VIZCAYA STATE UNIVERSITY
Bayombong, Nueva Vizcaya
INSTRUCTIONAL MODULE
IM No.:IM-IT ECC4-2NDSEM-2021-2022

// Access elements of the Queue


int accessedNumber = numbers.peek();
System.out.println("Accessed Element: " + accessedNumber);

// Remove elements from the Queue


int removedNumber = numbers.poll();
System.out.println("Removed Element: " + removedNumber);

System.out.println("Updated Queue: " + numbers);


}
}

Output

Queue: [1, 5, 2]
Accessed Element: 1
Removed Element: 1
Updated Queue: [2, 5]

Java Queue Interface

Java Queue interface orders the element in FIFO(First In First Out) manner. In FIFO, first element is removed
first and last element is removed at last.

Queue Interface declaration


1. public interface Queue<E> extends Collection<E>

Methods of Java Queue Interface

Method Description

boolean It is used to insert the specified element into this queue and return
add(object) true upon success.

boolean It is used to insert the specified element into this queue.


offer(object)

Object remove() It is used to retrieves and removes the head of this queue.

Object poll() It is used to retrieves and removes the head of this queue, or
returns null if this queue is empty.

Object element() It is used to retrieves, but does not remove, the head of this queue.

Object peek() It is used to retrieves, but does not remove, the head of this queue,
or returns null if this queue is empty.

PriorityQueue class

“In accordance with Section 185, Fair Use of Copyrighted Work of Republic Act 8293, the copyrighted works included in this material may be reproduced for educational
purposes only and not for commercial distribution,”
NVSU-FR-ICD-05-00 (081220) Page 7 of 20
Republic of the Philippines
NUEVA VIZCAYA STATE UNIVERSITY
Bayombong, Nueva Vizcaya
INSTRUCTIONAL MODULE
IM No.:IM-IT ECC4-2NDSEM-2021-2022

The PriorityQueue class provides the facility of using queue. But it does not orders the elements in FIFO
manner. It inherits AbstractQueue class.

PriorityQueue class declaration

Let's see the declaration for java.util.PriorityQueue class.

1. public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable

Java PriorityQueue Example


1. import java.util.*;
2. class TestCollection12{
3. public static void main(String args[]){
4. PriorityQueue<String> queue=new PriorityQueue<String>();
5. queue.add("Amit");
6. queue.add("Vijay");
7. queue.add("Karan");
8. queue.add("Jai");
9. queue.add("Rahul");
10. System.out.println("head:"+queue.element());
11. System.out.println("head:"+queue.peek());
12. System.out.println("iterating the queue elements:");
13. Iterator itr=queue.iterator();
14. while(itr.hasNext()){
15. System.out.println(itr.next());
16. }
17. queue.remove();
18. queue.poll();
19. System.out.println("after removing two elements:");
20. Iterator<String> itr2=queue.iterator();
21. while(itr2.hasNext()){

1. System.out.println(itr2.next());
2. }
3. }
4. }
Test it Now
Output:head:Amit
head:Amit
iterating the queue elements:
Amit
Jai
Karan
Vijay
Rahul
after removing two elements:
“In accordance with Section 185, Fair Use of Copyrighted Work of Republic Act 8293, the copyrighted works included in this material may be reproduced for educational
purposes only and not for commercial distribution,”
NVSU-FR-ICD-05-00 (081220) Page 8 of 20
Republic of the Philippines
NUEVA VIZCAYA STATE UNIVERSITY
Bayombong, Nueva Vizcaya
INSTRUCTIONAL MODULE
IM No.:IM-IT ECC4-2NDSEM-2021-2022

Karan
Rahul
Vijay

Add Element to Deque

As mentioned in the beginning of this Java Deque tutorial, you can add elements to both the beginning and
end of a Deque. The Java Deque interface contains the following methods for adding elements to it:

 add()
 addLast()
 addFirst()
 offer()
 offerFirst()
 offerLast()

These methods will be explained in the following sections.

add()

You add elements to the beginning end of a Deque using the add() method. Here is an example of adding an
element to the end (tail) of a Java Deque:

Deque<String> deque = new ArrayDeque<>();

deque.add("element 1");

If the element cannot be inserted into the Deque, the add() method will throw an exception. This is different
from the offer() method, which will return false if it cannot insert the element.

The add() method is actually inherited from the Queue interface.

addLast()

The addLast() method also adds an element to the end (tail) of a Java Deque. This is the Deque interface's
equivalent of the add() method inherited from the Queue interface. Here is an example of adding an element to
a Java Deque instance using the addLast() method:

Deque<String> deque = new ArrayDeque<>();

deque.addLast("element 1");

If the element cannot be inserted into the Deque, the addLast() method will throw an exception. This is different
from the offerLast() method which will return false if the element cannot be added to the Deque.

addFirst()

To add an element at the beginning (head) instead of the end of a Java Deque you call the addFirst() method
instead. Here is an example of adding an element to the beginning (head) of a Java Deque:

Deque<String> deque = new ArrayDeque<>();

“In accordance with Section 185, Fair Use of Copyrighted Work of Republic Act 8293, the copyrighted works included in this material may be reproduced for educational
purposes only and not for commercial distribution,”
NVSU-FR-ICD-05-00 (081220) Page 9 of 20
Republic of the Philippines
NUEVA VIZCAYA STATE UNIVERSITY
Bayombong, Nueva Vizcaya
INSTRUCTIONAL MODULE
IM No.:IM-IT ECC4-2NDSEM-2021-2022

deque.addFirst("element 1");

If the element cannot be added to the beginning of the Deque, the addFirst() method will throw an exception.
This is different from the offerFirst() method which will return false if an element cannot be inserted in the
beginning of the Deque.

offer()

The offer() method adds an element to the end (tail) of the Deque. If adding the element succeeds
the offer() method returns true. If the adding the element fails - e.g. if the Deque is full, the offer() method
returns false. This is different from the add() method which will throw an exception is adding an element to the
end of the Deque fails. Here is an example of how to add an element to the end of a Java Deque using
the offer() method:

Deque<String> deque = new ArrayDeque<>();

deque.offer("element 1");

offerLast()

The offerLast() method adds an element to the end (tail) of the Deque, just like offer(). The method
name offerLast() is just a bit more saying about where the element is added to the Deque. If adding the
element succeeds the offerLast() method returns true. If the adding the element fails - e.g. if the Deque is full,
the offerLast() method returns false. This is different from the addLast() method which will throw an exception
is adding an element to the end of the Deque fails. Here is an example of how to add an element to the end of
a Java Deque using the offerLast() method:

Deque<String> deque = new ArrayDeque<>();

deque.offerLast("element 1");

offerFirst()

The offerFirst() method adds an element to the beginning (head) of the Deque. If adding the element succeeds
the offerFirst() method returns true. If the adding the element fails - e.g. if the Deque is full,
the offerFirst() method returns false. This is different from the addFirst() method which will throw an exception
is adding an element to the beginning of the Deque fails. Here is an example of how to add an element to the
beginning of a Java Deque using the offerFirst() method:

Deque<String> deque = new ArrayDeque<>();

deque.offerFirst("element 1");

push()

The push() method adds an element to the beginning (head) of a Java Deque method. If adding the

element fails, for instance if the Deque is full, the push() method will throw an exception. This is similar to how
the addFirst() method works. Here is an example of adding an element to the beginning of a Java Deque using
the push() method:

“In accordance with Section 185, Fair Use of Copyrighted Work of Republic Act 8293, the copyrighted works included in this material may be reproduced for educational
purposes only and not for commercial distribution,”
NVSU-FR-ICD-05-00 (081220) Page 10 of 20
Republic of the Philippines
NUEVA VIZCAYA STATE UNIVERSITY
Bayombong, Nueva Vizcaya
INSTRUCTIONAL MODULE
IM No.:IM-IT ECC4-2NDSEM-2021-2022

Deque<String> deque = new LinkedList<>();

deque.push("element 0");

Peek at Element in Deque

You can peek at the first and last elements of a Java Deque. Peeking at an element means obtaining a
reference to the element without removing the element from the Deque. You can peek at the first and last
element of a Java Deque using these methods:

 peek()
 peekFirst()
 peekLast()
 getFirst()
 getLast()

Both of these methods will be covered in the following sections.

peek()

The peek() method returns the first element from the beginning (head) of a Java Deque without removing it. If
the Deque is empty, peek() returns null. Here is an example of peeking at the first element of a
Java Deque using the peek() method:

Deque<String> deque = new ArrayDeque<>();

deque.add("first element");
deque.add("last element");

String firstElement = deque.peek();

After running this code the firstElement will point to the first String element added to the Deque: "first element".

peekFirst()

The peekFirst() method returns the first element from the beginning (head) of a Java Deque without removing
it. If the Deque is empty, peekFirst() returns null. This is similar to how peek() works, but the method
name peekFirst() is a bit more saying about which end of the Deque you peek at. Here is an example of
peeking at the first element of a Java Deque using the peekFirst() method:

Deque<String> deque = new ArrayDeque<>();

deque.add("first element");
deque.add("last element");

String firstElement = deque.peekFirst();

After running this code the firstElement will point to the first String element added to the Deque: "first element".

“In accordance with Section 185, Fair Use of Copyrighted Work of Republic Act 8293, the copyrighted works included in this material may be reproduced for educational
purposes only and not for commercial distribution,”
NVSU-FR-ICD-05-00 (081220) Page 11 of 20
Republic of the Philippines
NUEVA VIZCAYA STATE UNIVERSITY
Bayombong, Nueva Vizcaya
INSTRUCTIONAL MODULE
IM No.:IM-IT ECC4-2NDSEM-2021-2022

peekLast()

To peek at the last element of a Java Deque you can use the peekLast() method. If the Deque is
empty, peekLast() will return null. Here is an example of peeking at the last element of a Java Deque using
the peekLast() method:

Deque<String> deque = new ArrayDeque<>();

deque.add("first element");
deque.add("last element");

String lastElement = deque.peekLast();

After running this Java example, the variable lastElement will point to the String last element - since that String
was the last element added to the Deque.

getFirst()

The getFirst() method returns the first element from the beginning (head) of a Java Deque without removing it.
If the Deque is empty, getFirst() throws an exception. Here is an example of peeking at the first element of a
Java Deque using the getFirst() method:

Deque<String> deque = new ArrayDeque<>();

deque.add("first element");
deque.add("last element");

String firstElement = deque.getFirst();

After running this code the firstElement will point to the first String element added to the Deque: "first element".

getLast()

To peek at the last element of a Java Deque you can use the getLast() method. If the Deque is
empty, getLast() will return null. Here is an example of peeking at the last element of a Java Deque using
the getLast() method:

Deque<String> deque = new ArrayDeque<>();

deque.add("first element");
deque.add("last element");

String lastElement = deque.getLast();

After running this Java example, the variable lastElement will point to the String last element - since that String
was the last element added to the Deque.

Remove Element From Deque

To remove elements from a Java Deque, you can use one of the following methods:

“In accordance with Section 185, Fair Use of Copyrighted Work of Republic Act 8293, the copyrighted works included in this material may be reproduced for educational
purposes only and not for commercial distribution,”
NVSU-FR-ICD-05-00 (081220) Page 12 of 20
Republic of the Philippines
NUEVA VIZCAYA STATE UNIVERSITY
Bayombong, Nueva Vizcaya
INSTRUCTIONAL MODULE
IM No.:IM-IT ECC4-2NDSEM-2021-2022

 remove()
 removeFirst()
 removeLast()
 poll()
 pollFirst()
 pollLast()

Each of these methods will be explained in the following sections.

remove()

The remove() method removes the first element of a Java Deque. That is the element at the head of
the Deque. The remove() method is actually inherited from the Queue interface. The remove() method returns
the element that is removed from the Deque. Here is an example of removing the first element a
Java Deque using the remove() method:

Deque<String> deque = new LinkedList<>();

deque.add("element 0");

String removedElement = deque.remove();

If the Deque is empty, remove() will throw an exception. This is different from poll() which returns null if the
Deque is empty.

removeFirst()

The removeFirst() method also removes the first element from a Deque - the element at the head of
the Deque. Here is an example of removing the first element of a Java Deque using the removeFirst() method:

Deque<String> deque = new LinkedList<>();

deque.add("element 0");

String removedElement = deque.removeFirst();

If the Deque is empty, removeFirst() will throw an exception. This is different from pollFirst() which
returns null if the Deque is empty.

removeLast()

The removeLast() method removes the last element of a Deque - meaning the element at the tail of the Deque.
Here is an example of removing the last element of a Java Deque using the removeLast() method:

Deque<String> deque = new LinkedList<>();

deque.add("element 0");
deque.add("element 1");
deque.add("element 2");

String removedElement = deque.removeLast();

“In accordance with Section 185, Fair Use of Copyrighted Work of Republic Act 8293, the copyrighted works included in this material may be reproduced for educational
purposes only and not for commercial distribution,”
NVSU-FR-ICD-05-00 (081220) Page 13 of 20
Republic of the Philippines
NUEVA VIZCAYA STATE UNIVERSITY
Bayombong, Nueva Vizcaya
INSTRUCTIONAL MODULE
IM No.:IM-IT ECC4-2NDSEM-2021-2022

After running this Java example the removedElement variable will point to the String object element 2 - since
that element was the last element of the Deque when removeLast() was called.

If the Deque is empty, removeLast() will throw an exception. This is different from pollLast() which returns null if
the Deque is empty.

poll()

The poll() method removes an element from the beginning of the Deque. If the Deque is
empty, poll() returns null. This is different than remove() which throws an exception if the Deque is empty. Here
is an example of removing the first element from a Java Deque using the poll() method:

Deque<String> deque = new LinkedList<>();

deque.add("element 0");
deque.add("element 1");
deque.add("element 2");

String removedElement = deque.poll();

pollFirst()

The pollFirst() method removes an element from the beginning of the Deque, just like poll(). The method
name pollFirst() is just a bit more saying about from where the method removes elements. If the Deque is
empty, pollFirst() returns null. This is different than removeFirst() which throws an exception if the Deque is
empty. Here is an example of removing the first element from a Java Deque using the pollFirst() method:

Deque<String> deque = new LinkedList<>();

deque.add("element 0");
deque.add("element 1");
deque.add("element 2");

String removedElement = deque.pollFirst();

pollLast()

The pollLast() method removes an element from the end (tail) of the Deque. If the Deque is
empty, pollLast() returns null. This is different than removeLast() which throws an exception if the Deque is
empty. Here is an example of removing the last element from a Java Deque using the pollLast() method:

Deque<String> deque = new LinkedList<>();

deque.add("element 0");
deque.add("element 1");
deque.add("element 2");

String removedElement = deque.pollLast();

pop()

The pop() method removes an element from the beginning (head) of a Java Deque. If removing the element
fails, for instance if the Deque is empty, the pop() method will throw an exception. This is similar to how

“In accordance with Section 185, Fair Use of Copyrighted Work of Republic Act 8293, the copyrighted works included in this material may be reproduced for educational
purposes only and not for commercial distribution,”
NVSU-FR-ICD-05-00 (081220) Page 14 of 20
Republic of the Philippines
NUEVA VIZCAYA STATE UNIVERSITY
Bayombong, Nueva Vizcaya
INSTRUCTIONAL MODULE
IM No.:IM-IT ECC4-2NDSEM-2021-2022

the removeFirst() method works. Here is an example of removing the first element from a Java Deque using
the pop() method:

Deque<String> deque = new LinkedList<>();

deque.push("element 0");

String removedElement = deque.pop();

Check if Deque Contains Element

You can use the Java Deque contains() method to check if a Deque contains a given element.
The contains() method will return true if the Deque contains the element, and false if not. Here is an example of
checking if a Java Deque contains a specific element using the contains() method:

Deque<String> deque = new ArrayDeque<>();

deque.add("first element");

boolean containsElement1 = deque.contains("first element");


boolean containsElement2 = deque.contains("second element");

After running this code the containsElement1 variable will have the value true because the Deque contains
the Java String "first element", and the containsElement2 will contain the value false because the Deque does
not contains the String element "second element".

Deque Size

The Java Deque size() method returns the number of elements stored in the Java Deque at the time you
invoke the method. Here is an example of obtaining the number of elements in a Java Deque using
its size() method:

Deque<String> deque = new ArrayDeque<>();

deque.add("first element");
deque.add("second element");

int size = deque.size();

After running this code the size variable will contain the value 2 because the Deque contains 2 element at the
time size() is called.

Iterate Elements of Deque

You can also iterate all elements of a Java Deque, instead of just processing the elements one at a time. You
can iterate the elements of a Deque in two ways:

 Using an Iterator.
 Using the for-each loop.
“In accordance with Section 185, Fair Use of Copyrighted Work of Republic Act 8293, the copyrighted works included in this material may be reproduced for educational
purposes only and not for commercial distribution,”
NVSU-FR-ICD-05-00 (081220) Page 15 of 20
Republic of the Philippines
NUEVA VIZCAYA STATE UNIVERSITY
Bayombong, Nueva Vizcaya
INSTRUCTIONAL MODULE
IM No.:IM-IT ECC4-2NDSEM-2021-2022

Both of these options will be explained in the following sections. Note, that the sequence in which the elements
are obtained during iteration depends on the concrete Deque implementation. However, the method to iterate
the elements is the same regardless of implementation.

Iterate Elements via Iterator

The first way of iterating the elements of a Deque is to obtain an Iterator from the Deque and iterate the
elements via that. Here is an example of iterating the elements of a Java Deque via an Iterator:

Deque<String> deque = new LinkedList<>();

deque.add("element 0");
deque.add("element 1");
deque.add("element 2");

Iterator<String> iterator = deque.iterator();


while(iterator.hasNext(){
String element = iterator.next();
}

Iterate Elements via For-Each Loop

The second way to iterate the elements of a Deque is to use the for-each loop in Java. Here is an example of
iterating the elements of a Java Deque via the for-each loop:

Deque<String> deque = new LinkedList<>();

deque.add("element 0");
deque.add("element 1");
deque.add("element 2");

for(String element : deque) {


System.out.println(element);
}

More Details in the JavaDoc

There is a lot more you can do with a Deque, but you will have to check out the JavaDoc for more details. This
text focused on the two most common operations: Adding / removing elements, and iterating the elements.

Sample Program:

Example 1: Java program to implement Stack

public class Queue {


int SIZE = 5;
int items[] = new int[SIZE];
int front, rear;

Queue() {
front = -1;
rear = -1;
“In accordance with Section 185, Fair Use of Copyrighted Work of Republic Act 8293, the copyrighted works included in this material may be reproduced for educational
purposes only and not for commercial distribution,”
NVSU-FR-ICD-05-00 (081220) Page 16 of 20
Republic of the Philippines
NUEVA VIZCAYA STATE UNIVERSITY
Bayombong, Nueva Vizcaya
INSTRUCTIONAL MODULE
IM No.:IM-IT ECC4-2NDSEM-2021-2022

// check if the queue is full


boolean isFull() {
if (front == 0 && rear == SIZE - 1) {
return true;
}
return false;
}

// check if the queue is empty


boolean isEmpty() {
if (front == -1)
return true;
else
return false;
}

// insert elements to the queue


void enQueue(int element) {

// if queue is full
if (isFull()) {
System.out.println("Queue is full");
}
else {
if (front == -1) {
// mark front denote first element of queue
front = 0;
}

rear++;
// insert element at the rear
items[rear] = element;
System.out.println("Insert " + element);
}
}

// delete element from the queue


int deQueue() {
int element;

// if queue is empty
if (isEmpty()) {
System.out.println("Queue is empty");
return (-1);
}
else {
// remove element from the front of queue
“In accordance with Section 185, Fair Use of Copyrighted Work of Republic Act 8293, the copyrighted works included in this material may be reproduced for educational
purposes only and not for commercial distribution,”
NVSU-FR-ICD-05-00 (081220) Page 17 of 20
Republic of the Philippines
NUEVA VIZCAYA STATE UNIVERSITY
Bayombong, Nueva Vizcaya
INSTRUCTIONAL MODULE
IM No.:IM-IT ECC4-2NDSEM-2021-2022

element = items[front];

// if the queue has only one element


if (front >= rear) {
front = -1;
rear = -1;
}
else {
// mark next element as the front
front++;
}
System.out.println( element + " Deleted");
return (element);
}
}

// display element of the queue


void display() {
int i;
if (isEmpty()) {
System.out.println("Empty Queue");
}
else {
// display the front of the queue
System.out.println("\nFront index-> " + front);

// display element of the queue


System.out.println("Items -> ");
for (i = front; i <= rear; i++)
System.out.print(items[i] + " ");

// display the rear of the queue


System.out.println("\nRear index-> " + rear);
}
}

public static void main(String[] args) {

// create an object of Queue class


Queue q = new Queue();

// try to delete element from the queue


// currently queue is empty
// so deletion is not possible
q.deQueue();

// insert elements to the queue


for(int i = 1; i < 6; i ++) {
q.enQueue(i);
“In accordance with Section 185, Fair Use of Copyrighted Work of Republic Act 8293, the copyrighted works included in this material may be reproduced for educational
purposes only and not for commercial distribution,”
NVSU-FR-ICD-05-00 (081220) Page 18 of 20
Republic of the Philippines
NUEVA VIZCAYA STATE UNIVERSITY
Bayombong, Nueva Vizcaya
INSTRUCTIONAL MODULE
IM No.:IM-IT ECC4-2NDSEM-2021-2022

// 6th element can't be added to queue because queue is full


q.enQueue(6);

q.display();

// deQueue removes element entered first i.e. 1


q.deQueue();

// Now we have just 4 elements


q.display();

}
}

Output

Queue is empty
Insert 1
Insert 2
Insert 3
Insert 4
Insert 5
Queue is full

Front index-> 0
Items ->
1 2 3 4 5
Rear index-> 4
1 Deleted

Front index-> 1
Items ->
2 3 4 5
Rear index-> 4

In the above example, we have implemented the queue data structure in Java.

To learn the working about the queue, visit Queue Data Structure.

Example 2: Implement stack using Queue interface

“In accordance with Section 185, Fair Use of Copyrighted Work of Republic Act 8293, the copyrighted works included in this material may be reproduced for educational
purposes only and not for commercial distribution,”
NVSU-FR-ICD-05-00 (081220) Page 19 of 20
Republic of the Philippines
NUEVA VIZCAYA STATE UNIVERSITY
Bayombong, Nueva Vizcaya
INSTRUCTIONAL MODULE
IM No.:IM-IT ECC4-2NDSEM-2021-2022

Java provides a built Queue interface that can be used to implement a queue.

import java.util.Queue;
import java.util.LinkedList;

class Main {

public static void main(String[] args) {


// Creating Queue using the LinkedList class
Queue<Integer> numbers = new LinkedList<>();

// enqueue
// insert element at the rear of the queue
numbers.offer(1);
numbers.offer(2);
numbers.offer(3);
System.out.println("Queue: " + numbers);

// dequeue
// delete element from the front of the queue
int removedNumber = numbers.poll();
System.out.println("Removed Element: " + removedNumber);

System.out.println("Queue after deletion: " + numbers);


}
}

Output

Queue: [1, 2, 3]
Removed Element: 1
Queue after deletion: [2, 3]

In the above example, we have used the Queue interface to implement the queue in Java. Here, we have

used the LinkedList class that implements the Queue interface.

 numbers.offer() - insert elements to the rear of the queue

 numbers.poll() - remove an element from the front of the queue

Notice, we have used the angle brackets <Integer> while creating the queue. It represents that the queue is of

the generic type.

“In accordance with Section 185, Fair Use of Copyrighted Work of Republic Act 8293, the copyrighted works included in this material may be reproduced for educational
purposes only and not for commercial distribution,”
NVSU-FR-ICD-05-00 (081220) Page 20 of 20

You might also like