實現方式,利用一個入隊
游標和一個出隊游標來定製一個
數組而構造一個環形佇列:
(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());
}
}