front==tail 队列为null
(tail+1)%capacity = front 队列满
/*
循环队列
front==tail 队列为null
front :首位的index
tail: 队列后的null位置
tail+1=front 或者 (tail+1) %c = front队列满
*/
public class LoopQueue<E> implements Queue<E> {
E [] data;
int front,tail;
int size;
public LoopQueue() {
this(10);
}
/**
* 总容积 比真正可以保存数据的个数多1
* @param capacity
*/
public LoopQueue(int capacity) {
this.data = (E[]) new Object[capacity+1];
front=0;
tail=0;
size=0;
}
public int getCapacity(){
return data.length-1;
}
@Override
public int getSize() {
return size;
}
@Override
public boolean isEmpty() {
return front==tail;
}
//出队(删除首位数据)
@Override
public E dequeue() {
if (isEmpty())
throw new IllegalArgumentException("Array is null");
E e = data[front];
data[front] = null;
front= (front+1)%data.length;
size--;
if (size==getCapacity()/4&&getCapacity()/2!=0)
resize(getCapacity()/2);
return e;
}
// 入队
@Override
public void enqueue(E e) {
//控件满了
if ((tail+1)% data.length==front){
resize(getCapacity()*2);
}
data[tail] =e;
tail = (tail+1)%data.length;
size++;
}
private void resize(int capacity) {
E [] newObj = (E[]) new Object[capacity+1];
//循环队列第一位 赋值给新数组的第一位
for (int i = 0; i < size; i++) {
newObj[i] = data[(i+front)%data.length];
}
data = newObj;
front=0;
tail = size;
}
//获取队首
@Override
public E getFront() {
if (isEmpty()){
throw new IllegalArgumentException("array is null");
}
E e = data[front];
return e;
}
@NonNull
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("LoopQueue");
stringBuilder.append(" front:[");
for (int i = front; i !=tail; i=(i+1)%data.length) {
stringBuilder.append(data[i]);
//不是最后一位
if ((i+1)%data.length!=tail) {
stringBuilder.append(", ");
}
}
stringBuilder.append("] tail");
return stringBuilder.toString();
}
public static void main(String[] args) {
LoopQueue<Integer> loopQueue = new LoopQueue<Integer>();
for (int i = 0; i < 10; i++) {
loopQueue.enqueue(Integer.valueOf(i));
System.out.println(loopQueue);
if (i%3==2){
loopQueue.dequeue();
System.out.println(loopQueue);
}
}
}
}
结果: