/**
* 顺序队列模拟
*
* @Author: gb.wang
* @Date 2020/5/18 13:54
* @Version 1.0
*/
public class ArrayQueue<T> {
// 定义一个数组
private Object[] arr;
// 对头指针
private int front;
//队尾指针
private int rear;
public ArrayQueue(int capacity) {
if (capacity <= 0) {
throw new IllegalArgumentException("容量不能小于0!");
}
arr = new Object[capacity];
//初始化对头 和队尾指针
this.front = 0;
this.rear = 0;
}
/**
* 显示队列所有的数据
*/
public void display() {
if (isEmpty()) {
throw new RuntimeException("队列为空!");
}
for (int i = 0; i < rear; i++) {
System.err.println(i + "----->" + arr[i]);
}
}
/**
* 往队列里面插入数据
*
* @param t 插入数据
*/
public void insert(T t) {
// 先判断下数组是否是满了
if (isFull()) {
throw new RuntimeException("队列已满!");
}
arr[rear] = t;
rear++;
}
/**
* 出对
*/
public T poll() {
if (isEmpty()) {
throw new RuntimeException("没有可出队的数据!");
}
return (T) arr[front++];
}
/**
* 判断队列是否为空。
*/
public boolean isEmpty() {
// 如果头和尾指针相同就是空队列
return this.rear == this.front;
}
/**
* 判断数组是否满了
*/
public boolean isFull() {
// 如果数组的length 等于rear,那么数组就满了
return this.rear == arr.length;
}
}