-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathStackArrayDynamic.java
51 lines (40 loc) · 1.22 KB
/
StackArrayDynamic.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
package com.houarizegai.datastructure.stack.dynamicarray;
import java.util.Arrays;
public class StackArrayDynamic<T> {
private Object[] data;
private int top;
public StackArrayDynamic() {
data = new Object[1];
this.top = -1;
}
public void push(T element) {
ensureCapacity(top + 2);
data[++top] = element;
}
public T pop() {
if(isEmpty()) { // stack is empty
return null;
}
T removedItem = (T) data[top--];
ensureCapacity(top);
return removedItem;
}
public int size() {
return this.top + 1;
}
public boolean isEmpty() {
return (top == -1);
}
public void ensureCapacity(int minCapacity) {
int oldCapacity = data.length;
if(minCapacity > oldCapacity) {
int newCapacity = oldCapacity * 2;
if(newCapacity < minCapacity) // when delete all item and need to add element (if size style 0)
newCapacity = minCapacity;
data = Arrays.copyOf(data, newCapacity);
} else if(minCapacity <= oldCapacity / 2) {
int newCapacity = oldCapacity / 2;
data = Arrays.copyOf(data, newCapacity);
}
}
}