-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleQueue.java
More file actions
61 lines (48 loc) · 826 Bytes
/
Copy pathSimpleQueue.java
File metadata and controls
61 lines (48 loc) · 826 Bytes
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
@SuppressWarnings("unchecked")
public class SimpleQueue<Thing>{
Thing[] q;
int n = 0; // size of queue
int head = 0;
int tail = 0;
SimpleQueue(){
q = (Thing[]) new Object[1];
}
public void enqueue(Thing item){
if (n == q.length){
resize(2*n);
}
q[tail] = item;
tail++;
if (tail == q.length)
tail = 0;
n++;
}
public Thing dequeue(){
if (isEmpty())
return null;
Thing item = q[head];
q[head] = null;
head++;
if (head == q.length)
head = 0;
n--;
return item;
}
public boolean isEmpty(){
return n == 0;
}
public int size(){
return n;
}
public void resize(int newSize){
Thing[] newQ = (Thing[]) new Object[newSize];
for (int i = 0; i < n; i++){
newQ[i] = q[tail++];
if (tail == q.length)
tail = 0;
}
tail = n;
head = 0;
q = newQ;
}
}