public class ResizingArrayStack<Item> implements Iterable<Item> {
private int N;
private Item[] a = (Item[]) new Object[10];
public Item pop() {
Item item = a[--N];
a[N] = null;
if (N > 0 && N == a.length / 4) {
resize(a.length / 2);
}
return item;
}
public void push(Item item) {
if (N == a.length) {
resize(a.length * 2);
}
a[N++] = item;
}
private void resize(int newSize) {
Item[] temp = (Item[]) new Object[newSize];
for (int i = 0; i < N; i++) {
temp[i] = a[i];
}
a = temp;
}
public Boolean isEmpty() {
return N == 0;
}
public int size() {
return N;
}
@Override
public Iterator<Item> iterator() {
return new ReverseArrayIterator();
}
private class ReverseArrayIterator implements Iterator<Item> {
private int i;
@Override
public boolean hasNext() {
return i > 0;
}
@Override
public void remove() {
}
@Override
public Item next() {
return a[--i];
}
}
}
|