1.1 队列的数据结构
队列是一种特殊的
线性表
,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头。
1.2 Java 实现
public class ArrayQueue {
private static final int DEFAULT_SIZE = 10;
private Object[] queue; //队列
private int front; //头指针
private int rear; //尾指针
private int length; //队列长度
public ArrayQueue() {
length = DEFAULT_SIZE;
init();
}
public ArrayQueue(int length){
this.length = length;
init();
}
private void init(){
queue = new Object[length];
front = 0;
rear = 0;
}
public boolean isEmpty(){
return front == rear;
}
public boolean isFull(){
return (rear - front + length)%length == length;
}
public int size(){
return (rear - front + length)%length;
}
public void put(Object obj) throws Exception{
if (isFull()) {
throw new Exception("入队失败,队列已满");
}
queue[rear] = obj;
rear = (rear + 1)%length;
}
public Object get() throws Exception{
if (isEmpty()) {
throw new Exception("出队失败,队列为空");
}
Object obj = queue[front];
queue[front] = null;
front = (front + 1)%length;
return obj;
}
public void clear(){
queue = null;
init();
}
}