这一篇文章是上一篇文章的改进实现
使用计数器代替尾指针来使队列真正容量达到maxSize
队头指针:front
计数器: count;
队空条件:count == 0
队满条件:count == maxSize
进队操作:count++,(front+count)%masSize
出队操作:count--,front = (front+1)%maxSize
利用了计数器count,可以将队列的最大容量为maxSize,而不用空出一个单元
public class Queue<E> {
E[] queue;
int front;
int count;
int maxSize;
private final static int DEFAULT_SIZE = 10;
public Queue() throws Exception{
this(DEFAULT_SIZE);
}
public Queue(int capacity) throws Exception{
if(capacity < 0)
throw new Exception("Illegal capacity ");
queue = (E[]) new Object[capacity];
front = 0;
count = 0;
maxSize = capacity;
}
//--------元素进入队列算法----------
public boolean enQueue(E obj) throws Exception{
if(obj == null)
return false;
//判断是否队满
if(count == maxSize)
throw new Exception("Queue is full ");
//进队操作
count++;
queue[(front + count) % maxSize] = obj;
return true;
}
//------------元素出队算法---------------
public E deQueue() throws Exception{
//判断队空
if(count == 0)
throw new Exception("Queue is empty");
//出队操作
count--;
front = (front+1) % maxSize;
return queue[front];
}
//-------------判断队空算法--------------
public boolean isEmpty(){
return (count == 0) ? true:false;
}
//------------求队列元素个数算法-------------
public int countElem(){
return count;
}
//-------------输出队列算法----------------
public void display() throws Exception{
if(count == 0)
throw new Exception("Queue is empty ");
int index = (front+1)%maxSize;
int n = count;
while(n != 0){
System.out.println(queue[index]);
index = (index+1)%maxSize;
n--;
}
}
public static void main(String[] args) throws Exception{
Queue queue = new Queue(100);
for(int i=1;i<=100;i++)
queue.enQueue(i);
System.out.println("队列元素个数:" + queue.countElem());
System.out.println("队列是否为空:" + queue.isEmpty());
System.out.println("**********************************");
for(int i=1;i<=50;i++)
queue.deQueue();
System.out.println("队列元素个数:" + queue.countElem());
System.out.println("队列是否为空:" + queue.isEmpty());
System.out.println("**********************************");
for(int i=1;i<=50;i++)
queue.deQueue();
System.out.println("队列元素个数:" + queue.countElem());
System.out.println("队列是否为空:" + queue.isEmpty());
}
}