In: Computer Science
The following is the code for above question
public class Main{
public static void main(String[] args) {
CircularQueue q = new CircularQueue();
//Inserting 5 elements into the Circular Queue
q.enQueue(7);
q.enQueue(9);
q.enQueue(3);
q.enQueue(4);
q.enQueue(6);
//Deleting an item from Circular Queue from front
int[] element=q.deQueue(); //Store Deleted Element and next item index in element
if (element[0]!=-1) {
System.out.println("Deleted Element is " + (element[0]));
System.out.println("Next Element index is " + (element[1]));
}
q.display(); //display the elements in the circular Queue for reference
}
}
class CircularQueue {
int front,rear,SIZE=5;
int items[] = new int[SIZE];
CircularQueue() {
front = -1;
rear = -1;
SIZE=5;
}
CircularQueue(int SIZE)
{
this.front=-1;
this.rear=-1;
this.SIZE=SIZE;
}
boolean isFull() {
if (front==0 && rear==SIZE-1) {
return true;
}
if (front==rear + 1) {
return true;
}
return false;
}
boolean isEmpty() {
if (front==-1)
return true;
else
return false;
}
void display() {
int i;
if (isEmpty()) {
System.out.println("Empty Queue");
} else {
System.out.println("Elements in Circular Queue are : ");
for (i=front;i!=rear;i=(i+1)%SIZE)
System.out.print(items[i] + " ");
System.out.println(items[i]);
}
}
void enQueue(int element) {
if (isFull()) {
System.out.println("Queue is full");
} else {
if (front==-1)
front=0;
rear=(rear+1)%SIZE;
items[rear]=element;
System.out.println("Inserted " + element +" into Circular Queue");
}
}
int[] deQueue() {
int element;
if (isEmpty()) {
System.out.println("Queue is empty");
return new int[] {-1,-1};
} else {
element=items[front];
if (front==rear) {
front=-1;
rear=-1;
}
else {
front=(front+1)%SIZE;
}
return new int[] {element,front}; // Here i am returning deleted element and front because when an item is deleted, we set front to front+1, which means the next element.
}
}
}
I am also attaching the output for your reference.
Output:
Inserted 7 into Circular Queue Inserted 9 into Circular Queue Inserted 3 into Circular Queue Inserted 4 into Circular Queue Inserted 6 into Circular Queue Deleted Element is 7 Next Element index is 1 Elements in Circular Queue are : 9 3 4 6
#Please dont forget to upvote if you find the solution helpful. Thank you.