基于順序表的隊列:
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;
}
}
}
基于鏈表形式的有空再補充。