Skip to content

Commit 8861a66

Browse files
committed
ArrayQueue: dequeue is now O(1)
1 parent 78f0726 commit 8861a66

1 file changed

Lines changed: 26 additions & 21 deletions

File tree

src/main/lists/ArrayQueue.java

Lines changed: 26 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,57 +2,62 @@
22
* An implementation of queue using a static array.
33
*
44
* <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>
59
* Operations and their time complexities are:
610
* <ul>
711
* <li><code>enqueue</code>: O(1)</li>
8-
* <li><code>dequeue</code>: O(n)</li>
12+
* <li><code>dequeue</code>: O(1)</li>
913
* <li><code>peek</code>: O(1)</li>
1014
* </ul>
1115
*/
1216
public class ArrayQueue<T> {
1317
private Object[] array;
1418
private int length;
19+
private int frontIndex;
20+
private int rearIndex;
1521

16-
public ArrayQueue(int maxLength) {
17-
this.array = new Object[maxLength];
22+
public ArrayQueue(int capacity) {
23+
this.array = new Object[capacity];
1824
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;
1935
}
2036

2137
public ArrayQueue<T> enqueue(T data) {
2238
if (this.length == this.array.length)
2339
return this;
2440

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++;
2645
return this;
2746
}
2847

2948
public ArrayQueue<T> dequeue() {
3049
if (this.length == 0)
3150
return this;
3251

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;
3654

37-
this.array[i - 1] = null;
3855
this.length--;
3956
return this;
4057
}
4158

4259
@SuppressWarnings("unchecked")
4360
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];
5762
}
5863
}

0 commit comments

Comments
 (0)