class CircularQueue{
private char q[];
private int putloc, getloc;
public CircularQueue(int size){
q = new char[size+1];
putloc = getloc = 0;
}
public void put (char ch) {
if (putloc+1==getloc | ((putloc ==q.length-1) & (getloc==0))) {
System.out.println ("Queue is full.");
return;
}
putloc++;
if(putloc==q.length) putloc = 0;
q[putloc] = ch;
}
public char get() {
if (getloc == putloc){
System.out.println("Queue is empty.");
return (char) 0;
}
getloc++;
if(getloc==q.length) getloc =0;
return q[getloc];
}
}
I don't understand when the queue would be full.
If putloc == q.length-1
, it would be at the end of an array.
getloc == 0
would be at the beginning of the array.
So if put()
was called it would do putloc++
and go to q[0]
and put a value there.
They claim it would overwrite a value at q[0]
but if getloc == 0
then that means it already returned a value from that part of the array.
q[getloc]
immediately follows getloc++
so once getloc == 0
it will get a value from q[0]
leaving that space empty for putting new values.
So the next time get()
is called it would get a value from q[1]
.
Can someone please explain where my logic is wrong?