一、簡介
1.1 概念
隊列簡稱隊
–他同堆棧一樣,也是一種運算受限的線性表,其限制是僅允許在表的一端進行插入,而在表的另一端進行刪除;
在隊列中把插入數據元素的一端稱爲隊尾,刪除數據元素的一端稱爲隊頭;
向隊尾插入元素稱爲進隊和入隊,新元素入隊後成爲新的隊尾元素;從隊列中刪除元素稱爲離隊或出隊,元素出隊後,其後續元素成爲新的隊頭元素;
由於隊列的插入和刪除操作分別在隊尾和隊頭進行,每個元素必然按照進入的次序離隊,也就是說先進隊的元素必然先離隊,所以稱隊列爲先進先出表
。
循環隊列:
將數組的最後一個元素的下一個元素從邏輯上認爲是數組的第一個元素,這樣就形成了邏輯上的環 。
1.2 結構圖
二、簡單實現
public class CircleSequenceQueue {
static final int defaultSize = 10;
int front;
int rear;
int count;
int maxSize;
Object[] queue;
public CircleSequenceQueue() {
init(defaultSize);
}
public CircleSequenceQueue(int size) {
init(size);
}
public void init(int size) {
maxSize = size;
front = rear = 0;
count = 0;
queue = new Object[size];
}
public void append(Object obj) throws Exception {
if (count > 0 && front == rear) {
throw new Exception("隊列已滿!");
}
queue[rear] = obj;
rear = (rear + 1) % maxSize;
count++;
}
public Object delete() throws Exception {
if (isEmpty()) {
throw new Exception("隊列爲空!");
}
Object obj = queue[front];
front = (front + 1) % maxSize;
count--;
return obj;
}
public Object getFront() throws Exception {
if (!isEmpty()) {
return queue[front];
} else {
return null;
}
}
public boolean isEmpty() {
return count == 0;
}
}