環(huán)形隊列-數(shù)組簡單實現(xiàn)

package demo;

/**
 * ???????
 * 
 * @author Administrator
 *
 */
public class LoopQueue<E> {

    private E[] data;
    private int front, tail;
    private int size;
    private final static int growFactor = 2;
    private final static double compressThreadhold = 0.25;

    public LoopQueue() {
        this(10);
    }

    public LoopQueue(int capacity) {
        if (capacity <= 0)
            throw new IllegalArgumentException("????????С??0");
        data = (E[]) new Object[capacity + 1];
        front = 0;
        tail = 0;
        size = 0;
    }

    public int getCapacity() {
        return data.length - 1;
    }

    public int getSize() {
        return size;
    }

    public boolean isEmpty() {
        return front == tail;
    }

    public boolean isFull() {
        return (tail + 1) % data.length == front;
    }

    public void enQueue(E e) throws IllegalAccessException {
        if (e == null)
            throw new IllegalArgumentException("???????????");
        if (isFull())
            resize(data.length * growFactor);
        data[tail] = e;
        tail = (tail + 1) % data.length;
        size++;
    }

    public E deQueue() {
        E result = null;
        if (isEmpty())
            throw new IllegalAccessError("???????");
        result = data[front];
        front = (front + 1) % data.length;
        size--;
        if (size < (data.length * compressThreadhold))
            resize(data.length / growFactor);
        return result;
    }

    private void resize(int capacity) {
        E[] ndata = (E[]) new Object[capacity + 1];
        for (int i = 0; i < size; i++) {
            ndata[i] = data[(i + front) % data.length];
        }
        System.out.println("???????....");
        data = ndata;
        front = 0;
        tail = size;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("queue [");
        for (int i = front; i != tail; i = (i + 1) % data.length) {
            sb.append(data[i]);
            sb.append(" ,");
        }
        sb.append("] tail");
        return sb.toString();
    }

    public static void main(String[] args) throws Exception {
        LoopQueue<Integer> lq = new LoopQueue<Integer>();
        for (int i = 0; i < 50; i++) {
            lq.enQueue(i);
        }
        System.out.println(lq);
        System.out.println(lq.getCapacity() + ":" + lq.getSize());
        System.out.println("==================================");
        for (int i = 0; i < 40; i++) {
            lq.deQueue();
        }
        System.out.println(lq);
        System.out.println(lq.getCapacity() + ":" + lq.getSize());
    }

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容