import java.util.Iterator; /** * 动态数组实现下压栈 * 成员变量:容器数组arr,元素个数count * 私有方法:调整数组大小resize() * 公开方法:添加元素push()、删除元素pop()、获取大小size()、判断是否为空isEmpty() * 要求:实现泛型、迭代器、 */ public class ArrayStack<Item> implements Iterable<Item> { private Item[] arr; private int count; public ArrayStack() { arr = (Item[])new Object[5]; count = 0; } public ArrayStack(int n) { arr = (Item[])new Object[n]; count = 0; } private void resize(int size){ Item[] temp = (Item[])new Object[size]; for(int i=0;i<arr.length;i++){ temp[i]=arr[i]; } arr = temp; } public void push(Item e){ if(arr.length == count){ resize(2*arr.length); } arr[count]=e; count++; } public Item pop(){ if(count==0) return null; Item temp = arr[count-1]; arr[count-1]=null; count--; if(count<arr.length/2){ resize(arr.length/2); } return temp; } public int size(){ return count; } public boolean isEmpty(){ if(count==0) return true; return false; } @Override public Iterator<Item> iterator() { return new Iterator<Item>() { int i=count-1; @Override public boolean hasNext() { if(i>=0) return true; return false; } @Override public Item next() { return arr[i--]; } }; } }
/** * 测试案例 */ public class TestCase { public static void main(String[] args) { ArrayStack<Integer> integers = new ArrayStack<>(); integers.push(1); integers.push(2); integers.push(3); integers.push(4); integers.push(5); System.out.println(integers.pop()); System.out.println(integers.size()); System.out.println(integers.isEmpty()); System.out.println("======================"); for(Integer e :integers){ System.out.println(e); } } }
//结果 5 4 false ====================== 4 3 2 1