Circular Queue :
Circular Queue is a linear data structure. It follows FIFO principle.
- In Circular Queue the last node is connected back to the first node to make a circle.
- Elements are added at the rear and deleted at front of the queue.
- Both the front and rear pointers point to the beginning of the array.
- Circular Queue is also called as Ring Buffer.
- Items can be inserted and deleted from a queue in O(1) time.
Circular Queue can be created in three ways they are :
- Using arrays (In this post)
- Using single linked list
- Using double linked list
Program :
interface CQArrAdt{
void insert();
void delete();
void display();
}
class CQArr1 implements CQArrAdt{
int cq[],size,front,rear;
Scanner s=new Scanner(System.in);
public CQArr1()throws Exception{
System.out.println("Enter the size of the Circular Queue :");
size=s.nextInt();
cq=new int[size];
front=-1;rear=-1;
}
@Override
public void insert() {
if(((front==0) && (rear==cq.length-1))||(rear==front-1)){
System.out.println("Circular Queue is full!!!");
}
else if(front==-1){front=0;rear=0;}
else if(rear==cq.length-1)rear=0;//rotate/override cq
else
rear++;
System.out.println("Enter the element into the circular queue :");
int ele=s.nextInt();
cq[rear]=ele;
System.out.println("At this point rear= "+rear++);
}
@Override
public void delete() {
if(front==-1)
System.out.println("CQ is underflow!!");
else
{
System.out.println("Deleted item is :"+cq[front]);
if(front==rear)//array contains only one element
{
front=rear=-1;
}
else if(front==cq.length-1){//rotate in the array!!!
front=0;
}
else
front--;
}
}
@Override
public void display() {
if(front==-1){
System.out.println("CQ is empty");
}
else if(front<=rear){
for(int i=front;i<=rear;i++)
System.out.print(" a"+cq[i]);
}
else{
for(int i=front;i<cq.length;i++)
System.out.print(" b"+cq[i]);
for(int i=0;i<=rear;i++)
System.out.print(" c"+cq[i]);
}
}
}
public class CQArr{
public static void main(String args[]) throws Exception{
System.out.println("Circular Queue ADT");
Scanner s=new Scanner(System.in);
CQArr1 c=new CQArr1();
String ch="y";
while(ch.equalsIgnoreCase("y")){
System.out.println("Circular Queue operations\n1. Insert 2. Delete 3. Display 4. Exit\nEnter your choice :");
int opt=s.nextInt();
switch(opt){
case 1:c.insert();break;
case 2:c.delete();
break;
case 3:c.display();break;
case 4:System.exit(0);
default :System.out.println("Invalid operation!!!");
}
System.out.println("Do you want to continue (y/N):");
ch=s.next();
}
}
}
No comments:
Post a Comment