环形队列-数组简单实现
2022-04-04 本文已影响0人
与诗小睡
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());
}
}