In: Computer Science
Delete an item from a circular queue and return the index of the next item. (in Java)
The code below will insert, delete, and display the queue:
In queue, the inseretion only take place at end of queue and deletion only take place from the bigning. When deleting an elemnt from queue, the index of queue elements will be updated. So the index of next item after deletion of an item will become 1 in every situation.
import java.util.ArrayList;
public class CircQ{
//class variable declaration
private int size, front, rear;
//array list declaration of type integer
private ArrayList<Integer> q = new ArrayList<Integer>();
//constructor of circular queue
CircQ(int size)
{
this.size = size;
this.front = this.rear = -1;
}
//insertion function in queue
public void inQueue(int data)
{
//checking queue is full
if((front == 0 && rear == size - 1) ||
(rear == (front - 1) % (size - 1)))
{
System.out.print("Queue Full");
}
//checking queue empty
else if(front == -1)
{
front = 0;
rear = 0;
q.add(rear, data);
}
else if(rear == size - 1 && front != 0)
{
rear = 0;
q.set(rear, data);
}
else
{
rear = (rear + 1);
//add new element
if(front <= rear)
{
q.add(rear, data);
}
//updating old value in else case
else
{
q.set(rear, data);
}
}
}
//deletion function in queue and printing next index
public int deQueue()
{
int temp;
//check queue is empty
if(front == -1)
{
System.out.print("Queue Empty");
return -1;
}
temp = q.get(front);
//if queue has only one element
if(front == rear)
{
front = -1;
rear = -1;
}
else if(front == size - 1)
{
front = 0;
}
else
{
front = front + 1; //index updation
System.out.println("Next Index after updation of queue index: " + front); //printing next index after index updation
}
return temp;
}
//display elements in queue
public void dispQueue()
{
//check queue is empty
if(front == -1)
{
System.out.print("Queue Empty");
return;
}
System.out.print("Elements in circular queue: ");
if(rear >= front)
{
for(int i = front; i <= rear; i++)
{
System.out.print(q.get(i));
System.out.print(" ");
}
System.out.println();
}
else
{
//printing elements from front to max_size
for(int i = front; i < size; i++)
{
System.out.print(q.get(i));
System.out.print(" ");
}
//printing elements from 0th index till rear
for(int i = 0; i <= rear; i++)
{
System.out.print(q.get(i));
System.out.print(" ");
}
System.out.println();
}
}
// main function
public static void main(String[] args)
{
//initialising new object of queue
CircQ q = new CircQ(5);
//inserting 14,22,13,-6 to queue
q.inQueue(14);
q.inQueue(22);
q.inQueue(13);
q.inQueue(-6);
//displaying queue
q.dispQueue();
//deleting queue
int x = q.deQueue();
//check queue is empty
if(x != -1)
{
System.out.print("Deleted value = ");
System.out.println(x);
}
q.dispQueue();
}
}
OUTPUT:
here the queue entered is 14 22 13 -6.
deleting will delete the first element(14) from queue. The index of next item(22) will become 1.
And the new queue will be 22 13 -6