How to remove an element (dequeue) from the queue in Java? In the past article, I have described how to perform the enqueue in Java. In this chapter, we will go through the dequeue process. As you remember, in the queue type data structure, we have to remove the first element from the head.
Detailed implementation of the dequeue process. How to remove an element in the queue solution?
Let’s go in details through the process of removing an element in the queue data structure:
- Throw an exception if there is nothing to delete;
- Getting the value of the front element to return as a result;
- Moving the front pointer to the next element;
- We are checking if front equals null. We do that check for the case when its only one element in the queue. If we remove the last element in the queue, we need to make null the back pointer as well;
- Decrease the length of the queue by one;
- Return the value of the removed item;
Full code solution:
public int dequeue() {
//Throw exception if nothing to delete
if(queueIsEmpty()) {
throw new NoSuchElementException("Queue is empty");
}
//Extract the value to return
int result = front.data;
//Moving the front pointer to the next element
front = front.next;
//If the last element have been removed need to set the back pointer to null
if(front == null) {
back = null;
}
//Decrease the length of the queue by one
queueLength--;
//Return the result value
return result;
}
Dequeue animation:
In this section, we figured out how works dequeue in Java.
Full code and more examples in my facebook group.
Useful links:
Leave Any Questions Related To This Article Below!