Friday, April 27, 2012

15. CIRCULAR QUEUE IN JAVA



import java.util.*;
public class CircularQueue
{
    int front,rear,size=5;
    int a[]=new int[size];

    CircularQueue()
    {
        front=rear=size-1;
    }

    void Insert(int n)
    {
        Ins:
        {
        if(rear==size-1)
            rear=0;
        else rear++;
        if(rear==front)
        {
            System.out.println("Overflow");
            break Ins;
        }
        a[rear]=n;
        }
    }

    void Remove()
    {
    if(front==size-1)
        front=0;
    else ++front;
    if(front==rear)
        System.out.println("Queue Empty");
    }

    void Display()
    {
        System.out.print("Back -> ");
        int n=front+1;
        if(n==size)
            n=0;
        while(n<=rear)
        {
            System.out.print(a[n++] + " -> ");
            if(n==size)
                n=0;
        }
        System.out.println("Front");
    }

    public static void main(String[] args)
    {
        CircularQueue a=new CircularQueue();
        Scanner in=new Scanner(System.in);
        int val,ch;
        while (true)
        {
            System.out.println("Enter your Choice");
            System.out.println("\n-------------------------------------");
            System.out.println("1 : Add\t2 : Del\t3 : Display\t4 : Exit");
            ch=in.nextInt();
            switch(ch)
            {
                case 1:
                {
                    System.out.println("Enter Value To Insert");
                    val=in.nextInt();
                    a.Insert(val);
                    break;
                }
                case 2:
                {
                    a.Remove();
                    break;
                }
                case 3:
                {
                    a.Display();
                    break;
                }
                case 4: System.exit(0);
                default: continue;
            }
        }
    }
}