Two methods of java array to achieve circular queue

1. Distinguish between full queue and empty queue by vacant one element

public class ArrayQueueEmptyOneElement<T> {
    private int size = 0;

    private int startIndex = 0;

    private int endIndex = 0;

    private Object[] array = null;

    public ArrayQueueEmptyOneElement(int size) {
        //因为要空置一位,所以实际数组长度要加一
        this.size = size + 1;
        array = new Object[size + 1];
    }

    public boolean offer(T t){
        if (isFull()){
            System.out.println("队列已满。。。");
            return false;
        }
        array[endIndex] = t;
        endIndex = (endIndex + 1) % size;
        return true;
    }

    public T poll(){
        if (isEmpty()){
            System.out.println("队列是空的。。。");
            return null;
        }
        T t = (T) array[startIndex];
        array[startIndex] = null;
        startIndex = (startIndex + 1) % size;
        return t;
    }

    public boolean isFull(){
        return (endIndex + 1) % size == startIndex;
    }

    public boolean isEmpty(){
        return startIndex == endIndex;
    }
}

2. Judge whether the queue is full by the actual number of elements in the queue (no vacant elements)

public class ArrayQueueNoEmptyElement<T> {
    private int count = 0;

    private int startIndex = 0;

    private int endIndex = 0;

    private Object[] array = null;

    public ArrayQueueNoEmptyElement(int size) {
        array = new Object[size];
    }

    public boolean offer(T t){
        if (isFull()){
            System.out.println("队列已满。。。");
            return false;
        }
        array[endIndex] = t;
        endIndex = (endIndex + 1) % array.length;
        count++;
        return true;
    }

    public T poll(){
        if (isEmpty()){
            System.out.println("队列是空的。。。");
            return null;
        }
        T t = (T) array[startIndex];
        array[startIndex] = null;
        startIndex = (startIndex + 1) % array.length;
        count--;
        return t;
    }

    public boolean isFull(){
        return count == array.length;
    }

    public boolean isEmpty(){
        return count == 0;
    }
}

Guess you like

Origin blog.csdn.net/noob9527/article/details/114284703