眾所周知,佇列是先進先出,隊尾進,隊頭出
那麼怎麼來實現雙端迴圈佇列呢?
我們知道實現迴圈佇列中比較難的地方隊尾進,隊頭出在於怎麼讓rear + 1就到陣列的front 或者 出隊的時候怎麼讓front到front 我們可以這樣:rear = (rear + 1) % length
或者front = (front + 1) % length這樣就完美解決問題
可是加上隊頭進,隊尾出這個功能後,出現的問題是隊尾和隊頭怎麼往前走
當隊頭在陣列的首元素時,從隊頭入隊勢必要從陣列的頭轉變到陣列的尾巴,同理
當隊尾在陣列的首元素時,從隊尾出隊勢必要從陣列的頭轉變到陣列的尾巴
我們可以通過this.front = (this.front + this.elem.length - 1) % this.elem.length;
實現隊頭入隊
通過this.rear = (this.rear + this.elem.length - 1) % this.elem.length;
實現隊尾出隊
下面是實現**:
class
mycirculardeque
/** adds an item at the front of deque. return true if the operation is successful. */
public
boolean
insertfront
(int value)
this
.front =
(this
.front +
this
.elem.length -1)
%this
.elem.length;
this
.elem[front]
= value;
return
true;}
/** adds an item at the rear of deque. return true if the operation is successful. */
public
boolean
insertlast
(int value)
this
.elem[
this
.rear]
= value;
this
.rear =
(this
.rear +1)
%this
.elem.length;
return
true;}
/** deletes an item from the front of deque. return true if the operation is successful. */
public
boolean
deletefront()
this
.front =
(this
.front +1)
%this
.elem.length;
return
true;}
/** deletes an item from the rear of deque. return true if the operation is successful. */
public
boolean
deletelast()
this
.rear =
(this
.rear +
this
.elem.length -1)
%this
.elem.length;
return
true;}
/** get the front item from the deque. */
public
intgetfront()
return
this
.elem[
this
.front];}
/** get the last item from the deque. */
public
intgetrear()
if(this
.rear ==0)
return
this
.elem[
this
.rear -1]
;}/** checks whether the circular deque is empty or not. */
public
boolean
isempty()
return
false;}
/** checks whether the circular deque is full or not. */
public
boolean
isfull()
return
false;}
}
設計迴圈雙端佇列
題目描述 設計實現雙端佇列。你的實現需要支援以下操作 mycirculardeque k 建構函式,雙端佇列的大小為k。insertfront 將乙個元素新增到雙端佇列頭部。如果操作成功返回 true。insertlast 將乙個元素新增到雙端佇列尾部。如果操作成功返回 true。deletefro...
162 設計迴圈雙端佇列
題目描述 設計實現雙端佇列。你的實現需要支援以下操作 mycirculardeque k 建構函式,雙端佇列的大小為k。insertfront 將乙個元素新增到雙端佇列頭部。如果操作成功返回 true。insertlast 將乙個元素新增到雙端佇列尾部。如果操作成功返回 true。deletefro...
設計迴圈雙端佇列C
設計實現雙端佇列。你的實現需要支援以下操作 mycirculardeque k 建構函式,雙端佇列的大小為k。insertfront 將乙個元素新增到雙端佇列頭部。如果操作成功返回 true。insertlast 將乙個元素新增到雙端佇列尾部。如果操作成功返回 true。deletefront 從雙...