本文的代码来自于《数据结构与算法(JAVA语言版)》,是笔者在网上找到的资料,非正式出刊版物。笔者对代码一些比较难以理解的部分添加了注释和图解,欢迎大家来讨论。
重点理解通过取余运算将线性数组转换为循环数组
public class QueueArray implements Queue {
private static final int CAP = 7;//队列默认大小
private Object[] elements; //数据元素数组
private int capacity; //数组的大小elements.length
private int front; //队首指针,指向队首
private int rear; //队尾指针,指向队尾后一个位置
public QueueArray() {
this(CAP);
}
public QueueArray(int cap){
capacity = cap + 1;
elements = new Object[capacity];
front = rear = 0;
}
public int getSize() {
return (capacity-front+rear)%capacity;
}//返回队列的大小
public boolean isEmpty() {
return front==rear;
}//判断队列是否为空
public void enqueue(Object e) {
if (getSize()==capacity-1) expandSpace();
elements[rear] = e;
rear = (rear+1)%capacity;
}//数据元素e入队
private void expandSpace(){
Object[] a = new Object[elements.length*2];
int i = front;
int j = 0;
while (i!=rear){
a[j++] = elements[i];
i = (i+1)%capacity;
}
elements = a;
capacity = elements.length;
front = 0;
rear = j;
}
//队首元素出队
public Object dequeue() throws QueueEmptyException {
if (isEmpty())
throw new QueueEmptyException("错误:队列为空");
Object obj = elements[front];
elements[front] = null;
front = (front+1)%capacity;
return obj;
}
//取队首元素
public Object peek() throws QueueEmptyException {
if (isEmpty())
throw new QueueEmptyException("错误:队列为空");
return elements[front];
}
}
package dsa.adt;
import dsa.exception.QueueEmptyException;
public interface Queue {
//返回队列的大小
public int getSize();
//判断队列是否为空
public boolean isEmpty();
//数据元素e入队
public void enqueue(Object e);
//队首元素出队
public Object dequeue() throws QueueEmptyException;
//取队首元素
public Object peek() throws QueueEmptyException;
}
public class QueueEmptyException extends RuntimeException {
public QueueEmptyException(String err) {
super(err);
}
}