一、通过空置一个元素区分队列满和队列空
public class ArrayQueueEmptyOneElement<T> {
private int size = 0;
private int startIndex = 0;
private int endIndex = 0;
private Object[] array = null;
public ArrayQueueEmptyOneElement(int size) {
//因为要空置一位,所以实际数组长度要加一
this.size = size + 1;
array = new Object[size + 1];
}
public boolean offer(T t){
if (isFull()){
System.out.println("队列已满。。。");
return false;
}
array[endIndex] = t;
endIndex = (endIndex + 1) % size;
return true;
}
public T poll(){
if (isEmpty()){
System.out.println("队列是空的。。。");
return null;
}
T t = (T) array[startIndex];
array[startIndex] = null;
startIndex = (startIndex + 1) % size;
return t;
}
public boolean isFull(){
return (endIndex + 1) % size == startIndex;
}
public boolean isEmpty(){
return startIndex == endIndex;
}
}
二、通过队列中实际元素个数判断队列是否满(无空置元素)
public class ArrayQueueNoEmptyElement<T> {
private int count = 0;
private int startIndex = 0;
private int endIndex = 0;
private Object[] array = null;
public ArrayQueueNoEmptyElement(int size) {
array = new Object[size];
}
public boolean offer(T t){
if (isFull()){
System.out.println("队列已满。。。");
return false;
}
array[endIndex] = t;
endIndex = (endIndex + 1) % array.length;
count++;
return true;
}
public T poll(){
if (isEmpty()){
System.out.println("队列是空的。。。");
return null;
}
T t = (T) array[startIndex];
array[startIndex] = null;
startIndex = (startIndex + 1) % array.length;
count--;
return t;
}
public boolean isFull(){
return count == array.length;
}
public boolean isEmpty(){
return count == 0;
}
}