简体   繁体   中英

Circular Array Queue

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;
    }

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM