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());
}
}
}
循环队列模板(LoopQueue)
最新推荐文章于 2021-03-29 21:24:56 发布