本文實例講述了java數據結構與算法之雙向循環隊列的數組實現方法。分享給大家供大家參考,具體如下:
需要說明的是此算法我并沒有測試過,這里給出的相當于偽代碼的算法思想,所以只能用來作為參考!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
package source; public class Deque { private int maxSize; private int left; private int right; private int nItems; private long [] myDeque; //constructor public Deque( int maxSize){ this .maxSize = maxSize; this .myDeque = new long [ this .maxSize]; this .nItems = 0 ; this .left = this .maxSize; this .right = - 1 ; } //insert a number into left side public void insertLeft( long n){ if ( this .left== 0 ) this .left = this .maxSize; this .myDeque[-- this .left] = n; this .nItems++; } //insert a number into right side public void insertRight( long n){ if ( this .right== this .maxSize- 1 ) this .right = - 1 ; this .myDeque[++ this .right] = n; this .nItems++; } //remove from left public long removeLeft(){ long temp = this .myDeque[ this .left++]; if ( this .left== this .maxSize) this .left = 0 ; this .nItems--; return temp; } //remove from right public long removeRight(){ long temp = this .myDeque[ this .right--]; if ( this .left==- 1 ) this .left = this .maxSize- 1 ; this .nItems--; return temp; } //return true if deQue is empty public boolean isEmpty(){ return ( this .nItems== 0 ); } //return size of the deQue public int size(){ return this .nItems; } } |
PS:雙向循環隊列的用處很大,可以做為普通隊列,也可以用來做棧來用!
希望本文所述對大家java程序設計有所幫助。