Queue

Queue implementation using an array in Java

import java.io.*;
class Queue
{
int que[ ];
int size,front,rear;
  
Queue(int n)
{
size=n;
que = new int[size];
front=-1;
rear=-1;
}

void insert(int x)
{
    if(rear == size-1)
        System.out.println("Overflow");
    else if(front==-1 && rear==-1)
    {
        front++;
        rear++;
        que[rear]=x;
    }      
    else
    {
        rear++;
        que[rear]=x;
    }            
}

int delete()
{
    if(front==-1 && rear==-1)
    {
        System.out.println("Underflow");
        return -9999;
    }
    else if(front==rear)
    {
        int temp=que[front];
        front=-1;
        rear=-1;
        return temp;
    }
    else
    {
        int temp=que[front];
        front++;
        return temp;
    }
}

public void display()
{
    if(front==-1 && rear==-1)
        System.out.println("Empty queue");

    else
    {
        System.out.println("The queue is…");
        for(int i=front;i<=rear;i++)
            System.out.print(que[i]+" | ");
    }
    System.out.println("\n");
}

public static void main()throws IOException
{
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter the queue size");
    int s=Integer.parseInt(br.readLine());
    int t;
    Queue obj=new Queue(s);
    int k,ch,element;

    do
    {
    System.out.println("1. Add");
    System.out.println("2. Remove");
    System.out.println("3. Display");
    System.out.println("4. Quit");
    System.out.println("Enter choice ?");
    ch=Integer.parseInt(br.readLine());

    switch(ch)
    {    
        case 1:
            System.out.println("Enter the new element to be added at rear");
            element=Integer.parseInt(br.readLine());
            obj.insert(element);
            break;

        case 2:
            t=obj.delete();
            if(t!=-9999)
               System.out.println("Deleted "+t);
            break;

        case 3:
            obj.display();
            break;

        case 4:
            System.exit(0);

        default:
            System.out.println("Wrong choice… Re enter your choice");
    }

        System.out.println("Press 1 to continue and any other number to terminate");
        k=Integer.parseInt(br.readLine());

    } while(k==1);
}
}

Leave a Comment

Your email address will not be published. Required fields are marked *