700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > java 队列的数组_JAVA-循环数组实现简单的队列

java 队列的数组_JAVA-循环数组实现简单的队列

时间:2019-08-12 05:44:12

相关推荐

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;

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。