-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArrayBasedStack.java
47 lines (39 loc) · 989 Bytes
/
ArrayBasedStack.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
package com.adolfoeloy.datastructure.stack;
public class ArrayBasedStack<T> implements Stack<T> {
private T[] items;
private int n;
@SuppressWarnings("unchecked")
ArrayBasedStack(int capacity) {
items = (T[]) new Object[capacity];
}
@Override
public void push(T item) {
if (n == items.length) {
resize(n * 2);
}
items[n++] = item;
}
@Override
public T pop() {
T item = items[--n];
items[n] = null; // avoid loitering
if (n > 0 && n == items.length / 4) {
resize(n / 2);
}
return item;
}
@SuppressWarnings("unchecked")
private void resize(int newCapacity) {
T[] copy = (T[]) new Object[newCapacity];
if (n >= 0) System.arraycopy(items, 0, copy, 0, n);
items = copy;
}
@Override
public int size() {
return n;
}
@Override
public boolean isEmpty() {
return n == 0;
}
}