-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDynamicArray.java
68 lines (59 loc) · 1.04 KB
/
DynamicArray.java
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
public class DynamicArray {
private int data[];
private int nextIndex;
public DynamicArray() {
data = new int[5];
nextIndex = 0;
}
public int size() {
return nextIndex;
}
public void add(int element) {
if (nextIndex == data.length) {
restructure();
}
data[nextIndex] = element;
nextIndex++;
}
public void set(int index, int element) {
if (index > nextIndex) {
return;
}
if (index < nextIndex) {
data[index] = element;
} else {
add(element);
}
}
public int get(int index) {
if (index >= nextIndex) {
// error out
return -1;
}
return data[index];
}
public boolean isEmpty() {
if (size() == 0) {
return true;
} else {
return false;
}
}
public int removeLast() {
if (size() == 0) {
// error out
return -1;
}
int value = data[nextIndex - 1];
data[nextIndex - 1] = 0;
nextIndex--;
return value;
}
private void restructure() {
int temp[] = data;
data = new int[data.length * 2];
for (int i = 0; i < temp.length; i++) {
data[i] = temp[i];
}
}
}