-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathCircularArrayQueue.java
More file actions
70 lines (59 loc) · 1.68 KB
/
CircularArrayQueue.java
File metadata and controls
70 lines (59 loc) · 1.68 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.util.NoSuchElementException;
/**
* An implementation of a queue as a circular array
*
* Author: AnxietyMedicine (GitHub)
*/
public class CircularArrayQueue {
private Object[] elements;
private int head, tail, currentSize;
/**
* Constructs an empty queue
*/
public CircularArrayQueue() {
final int INITIAL_SIZE = 10;
elements = new Object[INITIAL_SIZE];
head = tail = currentSize = 0;
}
/**
* Adds an element to the tail of the queue
* @param newElement new element to add
*/
public void add(Object newElement) {
growIfNecessary();
currentSize++;
elements[tail] = newElement;
tail = (tail + 1) % elements.length;
}
/**
* Removes an element from the head of the queue
* @return removed element
*/
public Object remove() {
if (currentSize == 0) { throw new NoSuchElementException(); }
Object removed = elements[head];
head = (head + 1) % elements.length;
return removed;
}
/**
* Grows the element array if the current size equals the capacity
*/
private void growIfNecessary() {
if (currentSize == elements.length) {
Object[] newElements = new Object[2 * elements.length];
for (int i = 0; i < elements.length; i++) {
newElements[i] = elements[(head + i) % elements.length];
}
elements = newElements;
head = 0;
tail = currentSize;
}
}
/**
* Checks whether queue is empty
* @return true if queue is empty
*/
public boolean empty() {
return currentSize == 0;
}
}