public class CircularArrayQueue
{
private int[] elements;
private int head;
private int tail;
//初始化队列
public CircularArrayQueue(int initialCapacity) {
elements = new int[initialCapacity];
}
//进队列,按照队列先进先出原则,从队尾插入,e为插入的数值,队列满或操作失败抛异常IllegalStateException。
public boolean add(int e) throws IllegalStateException
{
boolean isFull = tail>head && (tail-head)%elements.length==0;
boolean isReachMaxInt = tail > elements.length && tail==Integer.MAX_VALUE;
boolean isAdded = false;
if(! isFull )
{
elements[tail%elements.length]=e;
if( isReachMaxInt )
{
tail = tail%elements.length;
head = head%elements.length;
}
tail++;
isAdded= true;
}
else
{
isAdded =false;
throw new IllegalStateException();
}
return isAdded;
}
//出队列,按照队列的先进先出原则,对头先出,队列为空或操作失败抛异常NoSuchElementException。
public int remove() throws NoSuchElementException
{
boolean isEmpty = tail==head;
int result=0;
if(! isEmpty)
{
result=elements[head%elements.length];
head++;
}
else
{
throw new NoSuchElementException();
}
return result;
}
//获取队列头数值,队列不变化
public int getQueueHeadElement() throws NoSuchElementException
{
int result = 0;
if(tail>head)
{
result=elements[head%elements.length];
}
else
{
throw new NoSuchElementException();
}
return result;
}
//获取队列尾数值,队列不变化
public int getQueueTailElement() throws NoSuchElementException
{
int result = 0;
if(tail>head)
{
result=elements[tail%elements.length-1];
}
else
{
throw new NoSuchElementException();
}
return result;
}
//获取队列长度
public int size()
{
return tail-head;
}
//查找数值value在队列中是否存在,如果存在返回true,否则返回false。
public boolean search(int value)
{
boolean isExist= false;
if(tail>head)
{
for(int index=head;index<tail;index++)
{
if(value==elements[index%elements.length])
{
isExist=true;
break;
}
}
}
return isExist;
}
}
热门评论
看了下jdk的源码,实现比我的要高级些,涉及到位操作
<<n 左移运算符 相当于乘以2的n次幂
>>n 右移运算符 相当于除以2的n次幂
<<<n 、>>>n 无符号位左/右移
initialCapacity |= (initialCapacity >>> 1);
initialCapacity |= (initialCapacity >>> 2);
initialCapacity |= (initialCapacity >>> 4);
initialCapacity |= (initialCapacity >>> 8);
initialCapacity |= (initialCapacity >>> 16);
initialCapacity++; 该运算可以得到大于initialCapacity最小2的N次幂数值
详情可参考 Queue实现类-->ArrayDeque 源码(实际上它的容量不存在满的时候,tail一直是下一个存储单元)