-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayQueue.java
More file actions
66 lines (55 loc) · 1.59 KB
/
ArrayQueue.java
File metadata and controls
66 lines (55 loc) · 1.59 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
import java.lang.reflect.Array;
import java.util.EmptyStackException;
// WARNING: growArray does not work as expected!
// There are two parts you need to copy to the new array in most cases: from 0 to tail, and from head to the end;
// from head to tail is just one of the possibilities (head happens to be 0)
public class ArrayQueue<T> implements Queue<T> {
T[] queue;
int head;
int tail;
int size = 10;
public ArrayQueue() {
T[] temp = (T[]) new Object[size];
queue = temp;
head = 0;
tail = 0;
}
public boolean empty() {
return head == tail;
}
public T dequeue() {
if(empty()) {
throw new EmptyStackException(); // or return NULL;
}
T temp = queue[head];
head = (head + 1) % queue.length;
return temp;
}
public void enqueue(T t) {
if (tail == size) {
growArray();
}
queue[tail] = t; // store t in last index
tail = (tail + 1); // advance tail index
}
public void growArray() {
T[] temp = (T[]) new Object[queue.length * 2];
size = (queue.length * 2)-1;
// // growing a circular array
// for(int i = head; i < queue.length; i++) {
// temp[i] = queue[i];
// }
// for(int i = 0; i < tail; i++) {
// temp[i] = queue[i];
// }
head = 0;
for(int scan = 0; scan < queue.length; scan++)
{
temp[scan] = queue[head];
head=(head+1);
}
head = 0;
tail = queue.length;
queue = temp;
}
}