package Queue;
public interface Queue_i <T>{
/**
* 出队
*/
T deQueue();
/**
* 入队
*/
void enQueue(T val);
/**
* 获取队头元素
*/
T getHead();
/**
* 获取队列长度
*/
int getLength();
/**
* 是否为空队列
*/
boolean isEmpty();
}
package Queue;
public class QueueImplement<T> implements Queue_i<T> {
//队头指针
private int front = 0;
//队尾指针
private int rear = 0;
//队列容量
private int maxSize = 0;
//队列元素个数
private int size = 0;
//循环队列的数组
private T[] loopArr;
public QueueImplement() {
this.loopArr = (T[]) new Object[10];
this.maxSize = 10;
}
public QueueImplement(int maxSize) {
this.loopArr = (T[]) new Object[maxSize];
this.maxSize = maxSize;
}
@Override
public T deQueue() {
if (this.isEmpty()) {
throw new RuntimeException("空队列");
}
T val = this.loopArr[front];
this.front = (this.front+1)%this.maxSize;
this.size--;
//检查是否需要缩容
if(this.size<(this.maxSize+1)/4&&this.maxSize>4) {
this.resetSize((this.maxSize+1) / 4);
}
return val;
}
@Override
public void enQueue(T val) {
if ((this.rear + 1) % this.maxSize == this.front) {
this.resetSize(this.maxSize * 2);
}
this.loopArr[this.rear] = val;
this.rear = (this.rear+1)% this.maxSize;
this.size++;
}
@Override
public T getHead() {
if (this.isEmpty()) {
throw new RuntimeException("空队列");
}
return this.loopArr[this.front];
}
@Override
public int getLength() {
if (this.isEmpty()) {
return 0;
}
return this.size;
}
@Override
public boolean isEmpty() {
return this.front == this.rear;
}
public int getMaxSize() {
return maxSize;
}
//修改数组容量
public void resetSize(int newMaxSize) {
T[] newLoopArr = (T[]) new Object[newMaxSize];
for (int i = 0; i < this.size; ++i) {
newLoopArr[i] = loopArr[(this.front + i) % maxSize];
}
this.front = 0;
this.rear = this.size;
this.loopArr = newLoopArr;
this.maxSize = newMaxSize;
}
}
自己写一个简单的测试文件