队列介绍
- 队列是一个有序列表,可以用 数组 或 链表 来实现
- 先进先出(FIFO),即先存入队列的数据,会先取出。后存入的数据后取出
数组实现环形队列
实现原理
- 定义两个指示器,一个指示器front数组记录第一个有效元素的位置;一个指示器tail记录最后一个有效原始的位置的后一位;
- 实际申请空间为 maxSize + 1(赋予成员变量maxSize);多出的这一空间作为留白,即tail指示的位置;
- 当front == tail 时,即都指向的是留白空间时,说明队列为空
- 当tail的后一个就是front,即(tail+1)%maxSize时,说明队列满了(留白空间永不放数据)
代码:
package queue;
public class CircleQueue<T> {
private int maxSize;
private int front = 0;
private int tail = 0;
private Object[] arr;
public CircleQueue(int maxSize) {
this.maxSize = maxSize+1;
arr = new Object[maxSize+1];
}
public boolean isFull() {
return (tail+1)%maxSize == front;
}
public boolean isEmpty() {
return front == tail;
}
public void addQueue(T t) {
if (isFull()) {
System.out.println("队列已满,不能添加数据...");
return;
}
arr[tail] = t;
tail = (tail+1)%maxSize;
}
@SuppressWarnings("unchecked")
public T popQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空...");
}
T ret = (T)arr[front];
front = (front+1)%maxSize;
return ret;
}
public void showQueue() {
if(isEmpty()){
System.out.println("队列空的,没有数据...");
return;
}
for (int i = front; i < front + size(); i++) {
System.out.printf("arr[%d]=%s\n", i%maxSize, arr[i%maxSize].toString());
}
}
public int size() {
return (tail + maxSize - front) % maxSize;
}
@SuppressWarnings("unchecked")
public T headQueue() {
return (T)arr[front];
}
}
源码地址,欢迎star