您的位置:首页 > 编程语言 > Java开发

Java数组实现可以动态增长的队列

2016-09-28 20:05 417 查看
队列是一种先进先出的数据结构,由队尾进入,由队头删除,类似于现实中的排队。用Java数组实现队列,用first和last分别指向队头和队尾,用storage数组存储元素,但是需要注意的是不同于堆栈,数组中的元素不一定全是队列中的元素,因为如果是一般的数组,first在最前面,last在最后,可能会出现first和last都在数组最后指向一个元素(整个队列只有一个元素),不能增加元素,但是前面的空间没法利用的情况。所以这里采用环形数组实现。另外考虑到队列容量需求会动态增加这里采用了动态数组实现队列扩容。关于数组容量增加请参考:数组容量动态增加。注意,删除队头元素,不是真正的删除,而是将元素排除在first和last索引之外,只有数组容量不够时,删除的元素才会被新元素覆盖。
  代码如下:
interface StdQueue<e>
{
public boolean isEmpty();
public boolean isFull();
public void  enQueue(E el);
public Object deQueue();
public void printAll();
void enLarge();
}

class StdArrayQue<e> implements StdQueue<e>
{
int first,last;
Object[] storage;
int inicap=4,step=4;//队列初始容量和增加时的步长
public StdArrayQue()
{
first=last=-1;
storage=new Object[inicap];
}
public boolean isEmpty() {

return first==-1;
}

@Override
public void enQueue(E el)
{
if(isFull())
{
enLarge();
System.out.println("队列容量不够,已动态增加数组容量到:"+storage.length);
}

if(last==storage.length-1||first==-1)
{
storage[0]=el;
last=0;
if(first==-1)
first=0;
}
else
storage[++last]=el;
}

@Override
public boolean isFull() {
return (first==0&&last==storage.length-1)||(first==last+1);
}

@Override

public Object  deQueue() {
// TODO Auto-generated method stub
Object temp=storage[first];
if(first==last)
first=last=-1;
else if(first==storage.length-1)
first=0;
else first++;
return temp;
}

@Override
public void printAll() {
for(Object i:storage)
System.out.print(i+"  ");
System.out.println();
}

@Override
public void enLarge() {
Object[] a=new Object[storage.length+step];
if(first==0&&last==storage.length-1)
System.arraycopy(storage, 0, a, 0, storage.length);
else
{
System.arraycopy(storage, 0, a, 0, last+1);
System.arraycopy(storage, first, a, a.length-storage.length+first, storage.length-first);

}
storage=a;
}

public static void main(String[] args)
{

StdArrayQue<integer> se=new StdArrayQue<>();
se.enQueue(1);
se.enQueue(2);
se.enQueue(3);
se.enQueue(4);
System.out.println("原始容量下,队列元素为");
se.printAll();

System.out.println("队列满后,继续增加元素5");
se.enQueue(5);
se.printAll();

se.deQueue();
System.out.println("删除队列首元素1,队列首元素为:"+se.storage[se.first]);

se.deQueue();

se.enQueue(6);
se.enQueue(7);
se.enQueue(8);
se.enQueue(9);
se.enQueue(10);
se.enQueue(11);
se.printAll();
}
}

</string>


运行程序如下:


参考来源:数据结构与算法 Adam Drozdek
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息