java实现的一个可以动态扩容的栈结构
public class TestStack {
//数据数组 private static String[] data;
//一个指针 private static int idx = 0; public TestStack(int size){ if(size <= 0){ throw new IllegalStateException("error size"); } data = new String[size]; } private void resize(){ if(idx < data.length){ return; } String[] old = data; data = new String[data.length * 2]; System.arraycopy(old, 0, data, 0, old.length); } public void push(String str){ resize(); data[idx] = str; idx++; } public String pop(){ if(idx == 0){ return null; } return data[--idx]; } public static void main(String[] args) { TestStack stack = new TestStack(1); for(int i =0;i <= 19; i++){ stack.push("a" + i); } for (int j =0 ; j <= 19;j++){ String str = stack.pop(); System.out.println(str); } } }