Queue implementation example in Java. How to implement a queue data structure in Java? First, you should know the queue works. It works the same principles as the real-life queue. If you come to the doctor, you should wait in line.
For instance, three people before you and you cam at 8.30. The first person came at 8, the second person came at 8.10, and the third person came at 8.20. So when the doctor calls the next to go in the first person that came at 8. That person will leave the line of waiting to go to the doctor. Simultaneously, the second person who arrived at 8.10 becomes the first person in the queue. That principle calls FIFO (First In First Out). Suppose somebody comes after you at 8.45. That person becomes the last after you. And the length of the queue will be increased by one. It is a linear process. The queue calls a linear data structure.
A simplistic illustration of queue implementation? The detailed solution in Java.
If you want to perform the queue data structure, you should follow the next steps:
- You will have to create a private class QueueNode. That class includes:
- Generic type variable that holds the value of the node;
- Queue node instance that reference to the next item after the current one. By default in the constructor is set to null;
private class QueueNode {
// Can be any or generic type
private int data;
// Reference to the next node
private QueueNode next;
public QueueNode(int data){
this.data = data;
// By default set next item reference to null
this.next = null;
}
}
- Implement a method that checks if the queue is empty or not;
// Method to check if the queue is empty
public boolean queueIsEmpty(){
return queueLength == 0;
}
- Implement a method to print the queue;
public void print() {
// If the queue is empty just exit
if(queueIsEmpty()) {
return;
}
// Set the pointer to the front node
QueueNode current = front;
while(current != null) {
System.out.print(current.data + " --> ");
current = current.next;
}
System.out.println("null");
}
In this section, we are not implementing to add an element and remove an element yet. Here we just focus on how the queue class supposes to looks like.
Full schema:
In this section, we are not implementing to add an element and remove an element yet. Here we just focus on how the queue class supposes to looks like.
Full code and more examples in my facebook group.
Useful links:
Leave Any Questions Related To This Article Below!