java 队列的数组_JAVA-循环数组实现简单的队列
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
{
if(value==elements[index%elements.length])
{
isExist=true;
break;
}
}
}
return isExist;
}
}
總結
以上是生活随笔為你收集整理的java 队列的数组_JAVA-循环数组实现简单的队列的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java打包后发布找不到jsp_ecli
- 下一篇: java 字节取位_java位 、字节