对于队列,他的重要性不亚于栈,而且往往队列和栈是配合着使用的,因为栈是后进先出,而队列是先进先出,这就导致了很多问题可能通过这两个数据结构进行魂环的调用来解决,当然,对于数组实现的队列,他的入队和出队都是非常迅速的,而且通常使用的队列都不是太大的,并且有了循环队列的想法,更是是的数组实现的队列有了更好的应用,下面废话不多说,上代码
package com.bird.three;
/**
* @category 队列的数组实现
* @author Bird
*
*/
public class QueueArray {
private Object[] theArray;
private int currentSize;
private int front;
private int back;
private static final int DEFAULT_CAPACITY = 10;
/**
* Construct
*/
public QueueArray(){
this(DEFAULT_CAPACITY);
}
public QueueArray(int capacity){
theArray = new Object[capacity];
makeEmpty();
}
public boolean isEmpty(){
return currentSize == 0;
}
public boolean isFull(){
return currentSize == theArray.length;
}
public void makeEmpty(){
currentSize = 0;
front = 0;
back = -1;
}
/**
* 插入新元素
* @param x为要插入的元素
* @exception 如果队满则抛出异常
*/
public void enQueue(Object x){
if(isFull())
throw new RuntimeException("队列已满");
back = increment(back);
theArray[back]= x;
currentSize++;
}
/**
* 处理队列的头尾游标,同时实现了循环队列,当游标到达数组头的时候直接赋值0转到数组头
* @param x数组的任何位置
* @return x+1;或者0(如果X为数组的头)
*/
private int increment(int x){
if(++x == theArray.length)
x = 0;
return x;
}
/**
* 返回并且移除队列的头元素
* @return 队列的头元素,或者null如果队列为空
*/
public Object deQueue(){
if(isEmpty())
return null;
currentSize--;
Object frontItem = theArray[front];
theArray[front]=null;
front = increment(front);
return frontItem;
}
}