How to add an element (enqueue) in the queue Java? In the previous article, I have explained how to implement the queue in Java. In this article, we will go through the adding elements process. As you remember, in the queue type data structure, we have to attach the new element to the queue’s last node.
Step-by-step enqueue Java implemention. How to add an element in the queue solution?
Let’s go step-by-step through the process of adding an element in the queue data structure:
- Create a temporary node for the new element;
- Set that new value to the head of the queue if the queue is empty;
- Otherwise, set the back element’s next item refers to the new temporary node;
- Move back pointer to the newly added element;
- Increase length by one;
Full code solution:
public void enqueue(int data) {
//Create temporary node with the new value
QueueNode temp = new QueueNode(data);
//If queue is empty set the new value to the head
if(queueIsEmpty()) {
front = temp;
} else {
//Otherwise set the temporary value to the reference of the back item
back.next = temp;
}
//Move back pointer
back = temp;
//Increase the length of the queue
queueLength++;
}
Enqueue animation:
In this section, we figured out how works enqueue in Java.
Full code and more examples in my facebook group.
Useful links:
Leave Any Questions Related To This Article Below!