用数组实现循环队列

//数组实现循环队列
public class ArrayQueue {
public Integer arr[];
public Integer start; //删除时start指针向前走一步。
public Integer end; //插入时end指针向前走一步。
public int size; //size只和array.length进行比较,目的是确定这个队列是否满了
public ArrayQueue(int initsize){ //数组初始化。
arr = new Integer[initsize];
start = 0;
end = 0;
size = 0;
}
public void push(int number){
if (size==arr.length){ //此时队列已满。
throw new ArrayIndexOutOfBoundsException("the Queue is full");
}
size++; //添加元素时size++;
arr[end] = number;
end = end==size-1?0:end+1; //判断是否达到了最火一个位置,如果达到了,则回到第一个位置。
}
public Integer poll(){
if (size==0){
throw new ArrayIndexOutOfBoundsException("the Queue is empty");
}
size--; //删除元素时size--;
int temp = start; //保留删除元素的索引,方便返回用。
start = start==size-1?0:start+1;
return arr[temp];
}
}
总结:1,因为是循环队列,所以加了一个size进行变量,每次添加元素时和arr.length进行判断。
2,使用双指针进行操作。
3,当指针到达末尾时,回到0位置。

猜你喜欢

转载自www.cnblogs.com/liuwentao/p/9358011.html