-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathArrayQueue.java
More file actions
68 lines (60 loc) · 1.66 KB
/
ArrayQueue.java
File metadata and controls
68 lines (60 loc) · 1.66 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
import java.util.Arrays;
import java.util.NoSuchElementException;
public class ArrayQueue {
Object[] array;
int length;
ArrayQueue() {
array = new Object[2];
length = 0;
}
public void insert(Object data) { // O(n) because of copy
if(length == 0) {
this.array[0] = data;
} else {
if(length >= array.length) {
array = Arrays.copyOf(array, array.length*2);
}
this.array[length] = data;
}
length++;
}
public Object remove() { // O(n) because copy
if(length == 0) throw new NoSuchElementException();
Object temp = array[0];
if(length == 1) {
array = null;
length--;
return temp;
}
if(length == 2) {
array[0] = array[1];
length--;
return temp;
}
array = Arrays.copyOfRange(array, 1, array.length-1);
length--;
return temp;
}
public Object check() { // O(1)
if(length == 0) throw new NoSuchElementException();
return array[0];
}
public ArrayQueue reverse() {
ArrayQueue queue = new ArrayQueue();
for(int i = this.length-1; i >= 0; i--) {
queue.insert(this.array[i]);
}
return queue;
}
@Override
public String toString() {
StringBuilder a = new StringBuilder("[ ");
for(int i = 0; i < length; i++) {
a.append(array[i]).append(" ");
}
return a + " ]";
}
public int size() { // O(1)
return length;
}
}