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;

}

}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部