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;
}
}
点击查看更多内容
1人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦