1 /*
2 note, here we use the concept of circle array: so head and tail could be in the middle of it.
3 head index is the 1st real value; tail index is the 1st available slot
4 h t
5 [...1 2 3 4 ....]
6 head: the first added value, the 1st index of meaningful value.
7 tail: points to the first available position to add new element
8 size: # of elements in array
9 when offer new element:
10 1) use the tail index
11 2) tail++. tricky: if tail++ == array.length: means the array is full(index out of bound), then move tail to 0
12 3) size++
13
14 when pop element:
15 1) return the head value
16 2) head++ tricky: if head++ == array.length(index out of bound) then move head to 0
17 3) tail--
18 4) size--
19 * */
20 public class UseArrayImplementQueueWithSize {
21 private int headIndex ;
22 private int tailIndex ;
23 private int size; //number of real value in array
24 private int[] array ; //the underlying buffer
25
26 public UseArrayImplementQueueWithSize(int cap) {
27 array = new int[cap] ;
28 headIndex = 0;
29 tailIndex = 0 ;
30 size = 0 ;
31 }
32
33 //add to the tailIndex
34 public boolean offer(int val){
35 //this means array reaches to the limit. adding number will causing losing number
36 if (size == array.length){
37 return false ;
38 }
39 array[tailIndex] = val ;
40 if (tailIndex +1 == array.length){
41 tailIndex = 0 ;
42 } else {
43 tailIndex++ ;
44 }
45 size++;
46 return true ;
47 }
48
49 //remove from the head, the hole will be filled with garbage value .
50 public Integer poll(){
51 //means there is no real value
52 if (this.size == 0){
53 return null ;
54 }
55 int value = array[headIndex] ;
56 if (headIndex + 1 == array.length){
57 headIndex = 0 ;
58 } else {
59 headIndex ++;
60 }
61 size-- ;
62 return value ;
63 }
64
65 public Integer peek(){
66 if (this.size == 0){
67 return null ;
68 }
69 return array[headIndex] ;
70 }
71
72 public boolean isEmpty(){
73 return this.size <= 0 ;
74 }
75
76 public int getSize(){
77 return this.size ;
78 }
79
80
81 public static void main(String[] args) {
82 UseArrayImplementQueueWithSize queue = new UseArrayImplementQueueWithSize(5) ;
83 queue.offer(5);
84 queue.offer(3);
85 System.out.println(queue.size); //2
86 System.out.println(queue.poll()); //5
87 System.out.println(queue.offer(4)); //true
88 System.out.println(queue.poll()); //3
89 }
90 }
![]()