I'm having some difficulty with fully implementing my Circular Array Queue with Java. Specifically, my enqueue is failing to queue the very last value inputted in my queue. I've tested dequeuing and re-enqueuing values and it worked fine until I tried inserting the last value, in which it would insert nothing.
I've already consulted with some TAs about what might be going wrong and have searched StackOverflow previous questions, and both yielded no positive results.
Any help would be greatly appreciated.
public class MyQueue {
public int queue[];
public int size;
public int rear;
public int front;
public MyQueue(int mySize) {
size = mySize;
queue = new int[size];
rear = 0;
front = 0;
}
public boolean isEmpty() {
if(rear == front || rear == -1) {
return true;
}
else {
return false;
}
}
public boolean isFull() {
if((rear + 1)% size == front) {
return true;
}
else
return false;
}
public void enqueueMod(int item) {
if (this.isFull()) {
return;
}
else {
queue[rear] = item;
rear = (rear + 1) % (size);
}
}
public int dequeueMod() {
int item = -99; //-99 so i know its empty
if(front == rear)
return item;
else {
item = queue[front];
queue[front] = 0;
front = (front +1 ) %size;
}
return item;
}
isFull
judgment is problematic. Suppose you initialize your queue with a size of 1, and then perform an enqueue
operation. At this time, isFull
will return true, cause you to be unable to enqueue this item.
public boolean isFull() {
if((rear + 1)% size == front) {
return true;
}
else
return false;
}
The simple solution is using an extra size
field to record the number of elements in the array:
public class MyQueue {
public int queue[];
public int size;
public int rear;
public int front;
public int actualSize;
public MyQueue(int mySize) {
size = mySize;
queue = new int[size];
rear = 0;
front = 0;
actualSize = 0;
}
public boolean isEmpty() {
return actualSize == 0;
}
public boolean isFull() {
return actualSize == size;
}
public void enqueueMod(int item) {
if (this.isFull()) {
return;
} else {
queue[rear] = item;
rear = (rear + 1) % (size);
actualSize++;
}
}
public int dequeueMod() {
int item = -99; //-99 so i know its empty
if (isEmpty())
return item;
else {
item = queue[front];
queue[front] = 0;
front = (front + 1) % size;
actualSize--;
}
return item;
}
}