Queue using LinkedList class in Java
Queue is a linear data structure which orders elements in a First-In-First-Out (FIFO) manner, where the first element inserted is the first one to be removed.
In this post, we’ll see how to implement a queue using the LinkedList class. Java provides the LinkedList class as part of the Java Collections Framework. For an overview of the Java Collections Framework, check out my post Overview of the Java Collections Framework.
Some important methods provided by the LinkedList class for implementing a queue are:
- add(E element)
- peek()
- poll()
- offer(E element)
- element()
- remove()
- isEmpty()
LinkedList class permits all elements, including null
. But it is not recommended to insert nulls because null
is used as a special return value by various methods to indicate that the deque is empty.
The following example demonstrates how to implement a queue using the LinkedList class.
Example
Output
Let us look at the methods available to us.
Methods
1) add(E element)
This method inserts an element at the end of the queue represented by this list. It returns true if the insertion is successful, or false if it is not.
If no space is currently available, this method throws an 'IllegalStateException'
.
2) peek()
It retrieves, but does not remove, the head of this queue (first element of this list). It returns null
if the queue is empty.
3) poll()
It retrieves and removes the head of this queue. In other words, it removes and returns the first element of this list.
If the queue is empty, it returns null
.
4) isEmpty()
This method tests if the queue is empty. It returns true if the queue is empty or false otherwise.
The methods offer(E element), element(), and remove() function similar to the methods add(E element), peek(), and poll() respectively but they don’t throw any exception if insertion is not possible, or return null
if the queue is empty.
Now since you know how to implement a queue using the LinkedList class, check out how to create a Queue using ArrayDeque.