队列 Queue 概述
队列作为一种常见的数据结构,它的特点是:先进先出,一端插入,一端删除。
定义
队列是一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,进行插入操作的端称为队尾, 进行删除操作 的端称为队头。
实现和细节
public class Queue<E> {
private int front;//队头一端,只允许删除
private int rear;//队尾一端,只允许插入操作
private int max_size = 16;
private Object[] data;
public Queue() {
this(10);
}
public Queue(int size) {
if (size < 0) {
throw new IllegalArgumentException("Queue init error,size is illegal:" + size);
}
this.max_size = size;
front = rear = 0;
data = new Object[max_size];
}
//判断是否为空
public boolean isEmpty() {
return rear == front ? true : false;
}
//入队
public boolean add(E e) {
if (rear == max_size) {
throw new RuntimeException("队列满了");
} else {
data[rear++] = e;
return true;
}
}
//返回队首元素,不删除元素
public E peek() {
if (isEmpty()) {
return null;
}
return (E) data[front];
}
//出队
public E poll() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
} else {
E e = (E) data[front];
data[front++] = null;
return e;
}
}
//长度
public int length() {
return rear - front;
}
}