-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStaticQueue.java
More file actions
82 lines (70 loc) · 1.57 KB
/
StaticQueue.java
File metadata and controls
82 lines (70 loc) · 1.57 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
71
72
73
74
75
76
77
78
79
80
81
82
package br.unisinos.queue;
public class StaticQueue<E> implements Queue<E> {
protected int first;
protected int last;
protected E elements[];
@SuppressWarnings("unchecked")
public StaticQueue(int maxSize) {
elements = (E[]) new Object[maxSize];
first = last = -1;
}
public boolean isEmpty() {
return first == -1;
}
public boolean isFull() {
return first == ((last + 1) % elements.length);
}
public int numElements() {
if (isEmpty())
return 0;
else {
int n = elements.length;
return ((n + last - first) % n) + 1;
}
}
public E front() throws UnderflowException {
if (isEmpty())
throw new UnderflowException();
return elements[first];
}
public E back() throws UnderflowException {
if (isEmpty())
throw new UnderflowException();
return elements[last];
}
public void enqueue(E element) throws OverflowException {
if (isFull())
throw new OverflowException();
else {
if (last == -1)
first = last = 0;
else
last = (last + 1) % elements.length;
elements[last] = element;
}
}
public E dequeue() throws UnderflowException {
if (isEmpty())
throw new UnderflowException();
E element = elements[first];
elements[first] = null;
if (first == last)
first = last = -1;
else
first = (first + 1) % elements.length;
return element;
}
public String toString() {
if (isEmpty())
return "[Empty]";
else {
String s = "[" + elements[first];
int n = numElements();
for (int i = 1; i < n; i++) {
int k = (first + i) % elements.length;
s += ", " + elements[k];
}
return s + "]";
}
}
}