(JAVA版實現:)
/**
* 環形佇列
* @author Zhongzhou Han
*/
public class CircularQueue {
//佇列原型數組
private Object[] queue;
//入隊與出隊游標
private int inIndex,outIndex = 0;
boolean empty,full;
public CircularQueue(int size) {
queue = new Object[size];
empty = true;
full = false;
}
/**
* 返回隊列長度
*/
public int length() {
return queue.length;
}
/**
* 入隊
*/
public boolean in(Object obj) {
if(isFull()) {
System.out.println("Waring: In queue failed! queue is full!");
return false;
}
//設定當前隊列入隊節點為傳入對象
queue[inIndex] = obj;
//指向下一個節點
nextInIndex();
return true;
}
/**
* 出隊
*/
public Object out() {
if(IsEmpty()) {
System.out.println("Waring: Out queue failed! queue is empty!");
return null;
}
//獲取當前出隊節點的對象
Object result = queue[outIndex];
//清空當前位置
queue[outIndex] = null;
//指向下一個節點
nextOutIndex();
return result;
}
/**
* 是否為空
*/
public boolean isEmpty() {
if(inIndex == outIndex && queue[inIndex] == null) {
return true;
}
return false;
}
/**
* 是否已滿
*/
public boolean isFull() {
if(inIndex == outIndex && queue[inIndex] != null) {
return true;
}
return false;
}
//入隊游標指向下一個節點
private int nextInIndex() {
if(inIndex + 1 < queue.length) {
inIndex += 1;
} else {
inIndex = 0;
}
return inIndex;
}
//出隊游標指向下一個節點
private int nextOutIndex() {
if(outIndex + 1 < queue.length) {
outIndex += 1;
} else {
outIndex = 0;
}
return outIndex;
}
//測試
public static void main(String args[]) {
CircularQueue test = new CircularQueue(4);
test.in(1);
test.in(2);
test.in(3);
test.in(4);
test.in(5);
System.out.println(test.out());
System.out.println(test.out());
System.out.println(test.out());
System.out.println(test.out());
System.out.println(test.out());
test.in(1);
test.in(2);
test.in(3);
System.out.println(test.out());
System.out.println(test.out());
System.out.println(test.out());
}
}