Thursday, 11 August 2016

Circular queue in java

import java.io.*;
class cirqueue
{
final int max=5;
int a[]=new int[max];
int front=-1,rear=-1;

void insert(int x)
{
    if((front==0 && rear==max-1 ) || (front==rear+1))
    {
    System.out.println("Queue is Full");
    }
    if(front==-1)
    {
        front=0;
        rear=0;
    }
    else
    {
    if(rear==max-1)
    rear=0;
    else
    rear=rear+1;
    }
    a[rear]=x;
}

void delete()
{
    if(front==-1)
    {
        System.out.println("queue is empty");
    }
System.out.println("The element deleted from the queue is:"+a[front]);
    if(front==rear)
    {
        front=-1;
        rear=-1;
    }
    else
    {
    if(front==max-1)
    front=0;
    else
    front=front+1;
    }


}

void display()
{
    int front_pos=front;
    int rear_pos=rear;
    if(front_pos==-1)
    {
        System.out.println("\n No element in Queue");
        return;
    }
    if(front_pos<=rear_pos)
    {
        while(front_pos<=rear_pos)
        {
            System.out.println(a[front_pos]+" "+front_pos++);
        }
        System.out.println();
    }
    else
    {
        while(front_pos<=max-1)
        {
            System.out.println(a[front_pos]+" ");
            front_pos++;
        }
        front_pos=0;
        while(front_pos<=rear_pos)
        {
            System.out.println(a[front_pos]+" ");
            front_pos++;
        }
    System.out.println();
    }
}
}
class circularqueueop
{
public static void main(String args[])throws IOException
{
int ch;int x;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
cirqueue cq=new cirqueue();
while(true)
{
System.out.println("\n1.Insertion");
System.out.println("2. Deletion");
System.out.println("3. Display");
System.out.println("4. Exit");
System.out.println("Enter your choice");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1: System.out.println("Enter the element to be inserted");
    x=Integer.parseInt(br.readLine());
    cq.insert(x);
    break;
case 2:    cq.delete();
    break;
case 3: cq.display();
    break;
case 4:System.exit(0);
}
}
}
}
Post a Comment