In: Computer Science
Java Code:
import java.util.*;
class queue
{
int rear,front;
int size;
int arr[];
queue(int n)
{
this.front=this.rear=-1;
this.size=n;
arr = new int[n];
}
void insert(int value)
{
//Queue is full
if((front == 0 && rear == -1) || (rear==(front-1)%(size-1)))
{
System.out.println("Queue is full\n");
return;
}
//Queue is empty inserting first element
else if(front == -1)
{
front = rear = 0;
arr[rear]=value;
}
//inserting after deletion
else if (rear == size-1 && front != 0)
{
rear = 0;
arr[rear] = value;
}
//normal insertion
else
{
rear++;
arr[rear] = value;
}
}
int delete()
{
//Queue is empty if front=-1
if(front == -1)
{
System.out.println("Queue is empty");
return -1;
}
//storing the deleting element in del
int del = arr[front];
//setting the index of deleted item to -1
arr[front]= -1;
if (front == rear)
{
front=rear=-1;
//after this Queue is empty
}
else if(front == size-1)
front=0;
else
front++;
return del;
}
void display()
{
int i;
if(front == -1)
//Queue is empty if front=-1
{
System.out.println("Queue is empty\n");
return;
}
System.out.println("Elements in circular Queue are:");
System.out.println("Element Index");
if(rear >= front)
//normally with doing circulation
{
for(i=front;i<=rear;i++)
{
System.out.println(arr[i]+" "+i);
}
}
else
{
for(i=front;i<size;i++)
System.out.println(arr[i]+" "+i);
for(i=0;i<=rear;i++)
System.out.println(arr[i]+" "+i);
}
}
}
public class Main
{
public static void main(String[] args) {
queue obj = new queue(4);
//inserting into Queue
obj.insert(2);
obj.insert(7);
obj.insert(9);
obj.display();
//Deleting from Queue
obj.delete();
obj.delete();
obj.display();
//Insertion after deletion
obj.insert(5);
obj.display();
//deleting all the Elements from queue
obj.delete();
obj.delete();
obj.display();
//insering 15 into empty queue
obj.insert(15);
obj.display();
}
}
Output:
If you have any queries, please comment below.
Please upvote , if you like this answer.