設計你的迴圈佇列實現。 迴圈佇列是一種線性資料結構,其操作表現基於 fifo(先進先出)原則並且隊尾被連線在隊首之後以形成乙個迴圈。它也被稱為「環形緩衝器」。
迴圈佇列的乙個好處是我們可以利用這個佇列之前用過的空間。在乙個普通佇列裡,一旦乙個佇列滿了,我們就不能插入下乙個元素,即使在佇列前面仍有空間。但是使用迴圈佇列,我們能使用這些空間去儲存新的值。
你的實現應該支援如下操作:
mycircularqueue(k): 構造器,設定佇列長度為 k 。
front: 從隊首獲取元素。如果隊列為空,返回 -1 。
rear: 獲取隊尾元素。如果隊列為空,返回 -1 。
enqueue(value): 向迴圈佇列插入乙個元素。如果成功插入則返回真。
dequeue(): 從迴圈佇列中刪除乙個元素。如果成功刪除則返回真。
isempty(): 檢查迴圈佇列是否為空。
isfull(): 檢查迴圈佇列是否已滿。
lass mycircularqueue
/** insert an element into the circular queue. return true if the operation is successful. */
public
boolean
enqueue
(int value)
this
.elem[
this
.rear]
= value;
this
.rear =
(this
.rear +1)
%this
.elem.length;
return
true;}
/** delete an element from the circular queue. return true if the operation is successful. */
public
boolean
dequeue()
this
.front =
(this
.front +1)
%this
.elem.length;
return
true;}
/** get the front item from the queue. */
public
intfront()
return
this
.elem[
this
.front];}
/** get the last item from the queue. */
public
intrear()
int index =
this
.rear ==0?
this
.elem.length-1:
this
.rear-1;
return
this
.elem[index];}
/** checks whether the circular queue is empty or not. */
public
boolean
isempty()
return
false;}
/** checks whether the circular queue is full or not. */
public
boolean
isfull()
return
false;}
}
資料結構 佇列 迴圈佇列
在佇列的陣列實現中,我們很容易發現數在出隊後,陣列的前面部分會有剩餘空間沒有被使用,所以我們為了最大程度的利用固定長度的陣列,我們採用迴圈佇列的儲存方式,這種方式的最大問題在於resize的時候比較麻煩,所以我們不考慮resize的情況。基本結構如下,這裡front指向第乙個元素的位置,rear指向...
資料結構 佇列 迴圈佇列
資料結構 佇列 迴圈佇列 順序儲存 犧牲乙個空間單元來判段佇列滿狀態。q.front q.rear 1 initsize date 2017 4 16 include define elemtype char define initsize 100 typedef structsqqueue voi...
資料結構 迴圈佇列
所謂順序儲存結構就是用一組位址連續的儲存單元依次存放從隊頭到隊尾的元素。宣告兩個指標rear front分別用來指示隊尾元素的下一位置和隊頭元素的位置。初始化時rear front 0 插入新的元素時尾指標加1,元素出佇列時隊頭指標加1。不過這樣做有個問題,不論是入隊還是出隊,隊頭或隊尾指標都是加1...