- 每项操作的用时都与集合大小无关
- 空间需求总是不超过集合大小乘以一个常数
public class MyStack<T> implements Iterable<T>{
private T[] items = (T[]) new Object[1]; //栈元素
private int N = 0;//元素数量
public boolean isEmpty(){
return N == 0;
}
public int size(){
return N;
}
public void reSize(int max){
T[] temp = items;
items = (T[]) new Object[max];
for(int i = 0 ;i < N ; i++){
items[i] = temp[i];
}
}
public void push(T item){
if(N == items.length)
reSize(2 * N);
items[N++] = item;
}
public T pop(){
T item = items[--N];
items[N] = null;
if(N > 0 && N == items.length/4)
reSize(items.length/2);
return item;
}
@Override
public Iterator<T> iterator() {
// TODO Auto-generated method stub
return new StackIterator();
}
class StackIterator implements Iterator<T>{
private int iteNum = N;
@Override
public boolean hasNext() {
// TODO Auto-generated method stub
return iteNum > 0;
}
@Override
public T next() {
// TODO Auto-generated method stub
return items[--iteNum];
}
}
}
代码实现参考《算法》第四版