用数组实现队列。首先需要:
队列头:last指针
队列尾:first指针
一般思路:
按照一般的思路,进队列一个数,first++。出队列一个数last++。当first和last碰头时,需要判断队列为空还是队列满了,当指针大于数组长度时,还需要做取余操作。经典操作中,两个指针之间的关系比较错综复杂。
新思路:
取一个size来保存当前数组中已经有多少元素。当入队列一个数,first++,同时size++;当出队列一个数,last++,同时size–;相当于,把原本复杂的关系,都和size联系起来了,将first指针和last指针之间的关系解耦,他们彼此无关联了,各自都只与size有关联。
这样就把问题转化了,只需要判断size的状态即可,当指针碰撞时,size为0,说明队列为空,size为数组长度,说明队列已满。
代码:
public static class ArrayQueue{
private Integer[] arr;
private Integer size;
private Integer first;
private Integer last;
public ArrayQueue(int initSize){
if(initSize<0){
throw new IllegalArgumentException("数组长度应该大于0");
}
arr=new Integer[initSize];
size=0;
first=0;
last=0;
}
public void push(int obj){
if(size==arr.length){
throw new ArrayIndexOutOfBoundsException("队列已满");
}
arr[first]=obj;
first=(first+1)%arr.length;
size++;
}
public Integer pop(){
if(size==0){
throw new ArrayIndexOutOfBoundsException("队列为空");
}
size--;
int temp=arr[last];
last=(last+1)%arr.length;
return temp;
}
public Integer peek(){
if(size==0){
throw new ArrayIndexOutOfBoundsException("队列为空");
}
return arr[last];
}
}