|
2 | 2 | * An implementation of queue using a static array. |
3 | 3 | * |
4 | 4 | * <p> |
| 5 | + * This implementation uses the cyclic buffer by storing the indices of the rear |
| 6 | + * and the front of the queue to achieve O(1) complexity on all operations. |
| 7 | + * |
| 8 | + * <p> |
5 | 9 | * Operations and their time complexities are: |
6 | 10 | * <ul> |
7 | 11 | * <li><code>enqueue</code>: O(1)</li> |
8 | | - * <li><code>dequeue</code>: O(n)</li> |
| 12 | + * <li><code>dequeue</code>: O(1)</li> |
9 | 13 | * <li><code>peek</code>: O(1)</li> |
10 | 14 | * </ul> |
11 | 15 | */ |
12 | 16 | public class ArrayQueue<T> { |
13 | 17 | private Object[] array; |
14 | 18 | private int length; |
| 19 | + private int frontIndex; |
| 20 | + private int rearIndex; |
15 | 21 |
|
16 | | - public ArrayQueue(int maxLength) { |
17 | | - this.array = new Object[maxLength]; |
| 22 | + public ArrayQueue(int capacity) { |
| 23 | + this.array = new Object[capacity]; |
18 | 24 | this.length = 0; |
| 25 | + this.frontIndex = 0; |
| 26 | + this.rearIndex = 0; |
| 27 | + } |
| 28 | + |
| 29 | + public int getLength() { |
| 30 | + return this.length; |
| 31 | + } |
| 32 | + |
| 33 | + public int getCapacity() { |
| 34 | + return this.array.length; |
19 | 35 | } |
20 | 36 |
|
21 | 37 | public ArrayQueue<T> enqueue(T data) { |
22 | 38 | if (this.length == this.array.length) |
23 | 39 | return this; |
24 | 40 |
|
25 | | - this.array[this.length++] = data; |
| 41 | + this.rearIndex = (this.rearIndex + 1) % this.array.length; |
| 42 | + this.array[this.rearIndex] = data; |
| 43 | + |
| 44 | + this.length++; |
26 | 45 | return this; |
27 | 46 | } |
28 | 47 |
|
29 | 48 | public ArrayQueue<T> dequeue() { |
30 | 49 | if (this.length == 0) |
31 | 50 | return this; |
32 | 51 |
|
33 | | - int i; |
34 | | - for (i = 1; i < this.length; i++) |
35 | | - this.array[i - 1] = this.array[i]; |
| 52 | + this.array[this.frontIndex] = null; |
| 53 | + this.frontIndex = (this.frontIndex + 1) % this.array.length; |
36 | 54 |
|
37 | | - this.array[i - 1] = null; |
38 | 55 | this.length--; |
39 | 56 | return this; |
40 | 57 | } |
41 | 58 |
|
42 | 59 | @SuppressWarnings("unchecked") |
43 | 60 | public T peek() { |
44 | | - return (T) this.array[0]; |
45 | | - } |
46 | | - |
47 | | - public static void main(String[] args) { |
48 | | - ArrayQueue<Integer> queue = new ArrayQueue<Integer>(10); |
49 | | - |
50 | | - for (int i = 0; i < 15; i++) |
51 | | - queue.enqueue(i); |
52 | | - |
53 | | - for (int i = 0; i < 20; i++) { |
54 | | - System.out.println(queue.peek()); |
55 | | - queue.dequeue(); |
56 | | - } |
| 61 | + return (T) this.array[this.frontIndex]; |
57 | 62 | } |
58 | 63 | } |
0 commit comments