Question

Im trying to implement a circular array queue without a count variable.

Im looking for a way to determine if the array is full, for it to call the expand method but it doesn't seem to be working any idea why? Thanks!

public void enqueue (T element) {
        if(front != (rear+1) % queue.length) {
            queue[rear] = element;
            rear = (rear+1) % queue.length;
        }
        else
            expandCapacity();
    }

public void expandCapacity() {
        T[] larger = ((T[]) (new Object[queue.length * 2]));

        for (int scan=0; scan < queue.length; scan++) {
            larger[scan] = queue[front];
            front = (front+1) % queue.length;
        }
        front = 0;
        rear = queue.length;
        queue = larger;
    }
Was it helpful?

Solution

The first thing i see that's wrong is that in the case where you need to expand, you don't ever add anything to the queue! The enqueue method needs to look like:

public void enqueue(T element) {
    if (front == (rear + 1) % queue.length) {
        expandCapacity();
    }
    queue[rear] = element;
    rear = (rear + 1) % queue.length;
}

In addition, in expandCapacity, you're setting rear to be one larger than you should; make it:

    rear = queue.length - 1;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top