基于顺序表的队列:
package StackExercise;
public class OrderQueue<T> {
//默认的最大长度
public static final int DEFAULT_SIZE = 20;
//最大长度
private int maxSize;
//当前队列
private Object[] objs;
//队列头
private int head;
//队列尾
private int tail;
//队列长度
private int size;
//初始化
public OrderQueue() {
this(DEFAULT_SIZE);
}
//初始化
public OrderQueue(int size) {
head = 0;
tail = 0;
maxSize = size;
objs = new Object[maxSize];
}
//获取队列长度
public int getLength() {
return size;
}
//出队
public T deQueue() {
T ret = null;
if (size <= 0) {
throw new RuntimeException("队列为空!");
} else {
size--;
ret = (T) objs[head];
objs[head] = null;
head = ++head % maxSize;
}
return ret;
}
//入队
public void enQueue(T t) {
if (size == maxSize) {
throw new RuntimeException("队列已满!");
} else {
size++;
objs[tail] = (Object) t;
tail = ++tail % maxSize;
}
}
//打印
public void print() {
int start = head;
while (start != tail) {
System.out.print(objs[start] + "\n");
start = ++start % maxSize;
}
}
}
基于链表形式的有空再补充。
网友评论