import java.util.Iterator;
/**
* 动态调整数组大小 下压栈实现
* @param <Item>
*/
public class LifoDemo<Item> implements Iterable<Item> {
private Item[] a = (Item[]) new Object[1];
private int N = 0;
public boolean isEmpty(){
return N == 0;
}
public int size(){
return N;
}
/**
* 实现数组动态
* @param max
*/
private void resize(int max){
Item[] temp = (Item[]) new Object[max];
for (int i = 0 ;i < N; i++)
temp[i] = a[i];
a = temp;
}
/**
* 添加元素
* @param item
*/
public void push(Item item){
if (a.length == N)
resize(2*a.length);
a[N++] = item;
}
/**
* 删除栈顶元素
* @return
*/
public Item pop(){
Item temp = a[--N];
int legth = a.length;
System.out.println(legth);
if (N>0 && N == a.length / 4)
resize(a.length / 2);
return temp;
}
public Iterator<Item> iterator() {
return new ReverArrayIterator();
}
private class ReverArrayIterator implements Iterator<Item>{
private int N;
public boolean hasNext(){
return N > 0;
}
public Item next(){
return a[--N];
}
}
public static void main(String[] args) {
LifoDemo<String> lifoDemo = new LifoDemo<>();
lifoDemo.push("ada");
System.out.println(lifoDemo.size());
lifoDemo.pop();
System.out.println(lifoDemo.size());
}
}