[英]Circular Queue Implementation in Java
我正在閱讀我在 Github 中偶然發現的隊列實現,並且很難理解為什么使用某些行為。 (可以在此處找到存儲庫的鏈接)
public ArrayQueue(int capacity) {
// ArrayQueue maximum size is data.length - 1.
data = new Object[capacity + 1];
front = 0;
rear = 0;
}
public void offer(T elem) {
if (isFull()) {
throw new RuntimeException("Queue is full");
}
data[rear++] = elem;
rear = adjustIndex(rear, data.length);
}
public T poll() {
if (isEmpty()) {
throw new RuntimeException("Queue is empty");
}
front = adjustIndex(front, data.length);
return (T) data[front++];
}
public boolean isFull() {
return (front + data.length - rear) % data.length == 1;
}
謝謝
ArrayQueue 最大大小為 data.length - 1。如果將數據數組視為循環,則變量的位置在邏輯上總是在變量 front 的前面。 所以前后組合的狀態數就是數據數組的長度。 並且總狀態之一用於判斷隊列是空的還是滿的。
read
是在后面調整的,因為rear
是應該添加新元素的地方。 添加元素后,它會遞增。 而front
是元素應該被彈出的索引,因為它已經有了元素。data.length - 1
所以如果隊列應該是滿的, front - rear
必須等於1
。我希望這回答了你的問題。 隨時在評論中提問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.