kumar Anny kumar Anny - 5 months ago 27
Java Question

Printing circular queue

How do we print circular queue in the below mentioned code.
After the queue is full and we remove one item and the insert the next item which comes at index 0.
How do we print it then?.
How do we print circular queue in the below mentioned code.

class GQueue <T extends Object>
{
T[] arr;
int size;
int front;
int rear;
int length;

GQueue(int size)
{
this.size=size;
arr=(T[])new Object[this.size];
front=-1;
rear=-1;
length=arr.length;
}

void EnQueue(T data)
{
if(isFull())
{
System.out.println("Queue full");
return;
}

else if(isEmpty())
front=rear=0;
else
rear = (rear+1)%length;

arr[rear]=data;
}

void DeQueue()
{
if(isEmpty())
return;
else if (front==rear)
{
front=rear=-1;
}
else
front=(front+1)%length;

}

T peek()
{

return arr[front];
}

boolean isEmpty()
{
if(front==-1 && rear==-1)
return true;
else
return false;


}

boolean isFull()
{
if( (rear+1) % length==front)
return true;
else
return false;

}

void print()
{
for(int i=front;i<=rear;i++)
{
System.out.print(arr[i]+" ");
}
System.out.println();
}
}





public class GenericQueue {

public static void main(String[] args) {
GQueue<Integer> gq = new GQueue<Integer>(10);
gq.EnQueue(1);
gq.EnQueue(2);
gq.EnQueue(3);
gq.EnQueue(4);
gq.EnQueue(5);
gq.EnQueue(6);
gq.EnQueue(7);
gq.EnQueue(8);
gq.EnQueue(9);
gq.EnQueue(10);


gq.print();
gq.DeQueue();
gq.EnQueue(11);
gq.print();
}


}

Answer
void print(){
    if (!isEmpty()) {
        int i = front;
        do {
            System.out.print(" " + arr[i];
            i = ++i % arr.length;
        while (i != rear);
    }
}

Not tested, but I think it's right, or at least gives the general idea.