循环队列模板(LoopQueue)

interface Queue<E> {
    boolean isEmpty();

    int getSize();

    void enQueue(E e);

    E deQueue();

    E getFront();
}

@SuppressWarnings("unchecked")
public class LoopQueue<E> implements Queue<E> {
    private E[] data;

    private int head, tail, size;

    public LoopQueue(int capacity) {
        data = (E[]) new Object[capacity];
        head = tail = size = 0;
    }

    public LoopQueue() {
        this(10);
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public void enQueue(E e) {
        data[tail] = e;
        tail = (tail + 1) % data.length;
        size++;
        if (size == data.length) {
            resize(data.length << 1);
        }
    }

    @Override
    public E deQueue() {
        checkEmpty();
        E ret = data[head];
        head = (head + 1) % data.length;
        size--;
        if (size == data.length >>> 2 && data.length >>> 1 != 0) {
            resize(data.length >>> 1);
        }
        return ret;
    }

    private void resize(int newCapacity) {
        E[] newData = (E[]) new Object[newCapacity];
        for (int i = 0; i < size; i++) {
            newData[i] = data[(i + head) % data.length];
        }
        data = newData;
        head = 0;
        tail = size;
    }

    private void checkEmpty() {
        if (isEmpty()) throw new IllegalArgumentException("Queue is empty.");
    }

    @Override
    public E getFront() {
        checkEmpty();
        return data[head];
    }

    public static void main(String[] args) {
        LoopQueue<Integer> lq = new LoopQueue<>();
        for (int i = 0; i < 100; i++) {
            lq.enQueue(i);
        }
        while (!lq.isEmpty()) {
            System.out.println(lq.deQueue());
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值