Queue Data Structure for Beginners

Queue is a kind of data structure where the order of the element matters. It’s like a line in-front of movie ticket line. The person who came last in the queue will stand at the rear position of the line. And the person who joined the line at the very first would be the person who gets his first tickets.

At first check the code, then it will be explained line by line:-

package stack_queue;

public class Queue {

	private int maxSize;
	private long[] queueArray;
	private int front;
	private int rear;
	private int nItems;
	
	
	public Queue(int s) {
		
		maxSize = s;
		queueArray = new long[maxSize];
		front = 0;
		rear = -1;
		nItems = maxSize;
		
		
	                     }
	
	public void insertItems(long d)
	{

		if (rear == maxSize-1)
		{
			rear = -1;
			 
		}
		
		queueArray[++rear] = d;
		System.out.println("rear value is " +  rear + " and the value is " + queueArray[rear]);
	}
	
	
	public long removeItems() {
		
		System.out.println("front position is " + front + " and the value is " + queueArray[front]);
		
		long temp = queueArray[front++];
		//To avoid the wrapping up
		if (front == maxSize) {
			
			front = 0 ;
			
		}
		
		return temp;
	}
	
	
	
public static void main (String [] args) {
	
	
	Queue k = new Queue(3);
	k.insertItems(12);
	k.insertItems(34);
	System.out.println(k.removeItems());
	System.out.println(k.removeItems());
	//k.removeItems();
	
}
}

Here to store the data of a queue one Linear data-structure Array is taken.

In the constructor the maximum size of the Array will be taken to define the array. Here two flags are taken, that is front and rear flag. Front flag’s value will start from zero and the rear flags value will start from the -1.

Array to store the queue

Now as we all know that the index of element always starts from the zero. And in the queue the item always adds from the rear position and gradually comes at the front. So the item will be added at rear after increasing the value of rear to zero.

So in insert methods, only this is done.

insert(20) , the 20 will be inserted at position zero. and the 2nd insert , insert(24) will insert the value at position 1.

Now remove method will return the first value that present at the position zero. Because the element present at zeroth position inserted first. And then it will return the value from index element 1 as shown in the picture below.

To avoid the wrapping up of the front element over the rear, when rear becomes array maximum size -1 and front position becomes at the maximum size of the array, we are resetting the entire values to again to rear = -1 and front = zero. And Please use the nItems properly, I have not included that in code. But it should to. For insertion increase it with +1 and for removal decrease it with -1.