Skip to content

Commit 78f0726

Browse files
committed
ArrayQueue: Add queue implementation using array
1 parent 54a1e7b commit 78f0726

1 file changed

Lines changed: 58 additions & 0 deletions

File tree

src/main/lists/ArrayQueue.java

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/**
2+
* An implementation of queue using a static array.
3+
*
4+
* <p>
5+
* Operations and their time complexities are:
6+
* <ul>
7+
* <li><code>enqueue</code>: O(1)</li>
8+
* <li><code>dequeue</code>: O(n)</li>
9+
* <li><code>peek</code>: O(1)</li>
10+
* </ul>
11+
*/
12+
public class ArrayQueue<T> {
13+
private Object[] array;
14+
private int length;
15+
16+
public ArrayQueue(int maxLength) {
17+
this.array = new Object[maxLength];
18+
this.length = 0;
19+
}
20+
21+
public ArrayQueue<T> enqueue(T data) {
22+
if (this.length == this.array.length)
23+
return this;
24+
25+
this.array[this.length++] = data;
26+
return this;
27+
}
28+
29+
public ArrayQueue<T> dequeue() {
30+
if (this.length == 0)
31+
return this;
32+
33+
int i;
34+
for (i = 1; i < this.length; i++)
35+
this.array[i - 1] = this.array[i];
36+
37+
this.array[i - 1] = null;
38+
this.length--;
39+
return this;
40+
}
41+
42+
@SuppressWarnings("unchecked")
43+
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+
}
57+
}
58+
}

0 commit comments

Comments
 (0)