-
Notifications
You must be signed in to change notification settings - Fork 28
/
StackArray.java
91 lines (69 loc) · 1.51 KB
/
StackArray.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package ds_004_stacks_and_queues;
public class StackArray<T> {
private static final int DEFAULT_CAPACITY = 10;
private int capacity;
private T[] collection;
private int index;
public StackArray(int capacity) {
this.capacity = capacity;
collection = (T[])new Object[capacity];
}
public StackArray() {
this(DEFAULT_CAPACITY);
}
public void push(T value) {
checkArray();
collection[index++] = value;
}
public T pop() {
checkArray();
return collection[--index];
}
private void checkArray() {
try {
if( index > (capacity/2) ) {
refresh(capacity*2);
return;
}
if(index < (capacity/2)) {
refresh(capacity/2);
return;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void refresh(int newCapacity) throws Exception {
if(newCapacity < index) {
throw new Exception("Invalid Collection Capacity");
}
this.capacity = newCapacity;
T[] newCollection = (T[])new Object[capacity];
for(int i = 0; i < index; i++) {
newCollection[i] = collection[i];
}
collection = newCollection;
}
// trivial methods
public int size() {
return index;
}
public int capacity() {
return capacity;
}
public boolean isEmpty() {
return index == 0;
}
public void print() {
System.out.print("Stack: ");
if(index == 0) {
System.out.print("EMPTY\n");
return;
}
for(int i = 0; i < index; i++) {
System.out.printf("%s ", collection[i]);
}
System.out.print("\n");
}
}