http://zhidao.baidu.com/question/273136809.html
public class Stack {
private Object[] stack;
//这个不需要;
//private int top = 0; //初始化栈顶
//这个也不需要;
//写一个栈出来,最好是可以动态的,可以自己改变大小的,即数组的长度;
//private int size = 0; // 初始化大小
//元素个数;
private int size;
//默认长度为10;
public Stack(){
this(10);
}
//也可以自己设置长度,即容量;
public Stack(int len){
stack = new Object[len];
}
//返回元素个数;
public int size(){
return size;
}
//返回数组长度,即容量;
public int capacity(){
return stack.length;
}
//实现动态的数组;
public void ensureCapacity(){
if(size() == capacity()){
Object[] newStack = new Object[size() * 3 / 2 + 1];
System.arraycopy(stack, 0, newStack, 0, size());
stack = newStack;
}
}
//入栈;
public void push(Object o){
size++;
ensureCapacity();
stack[size - 1] = o;
}
/*
public void push(Object object) {
if (isFull()) {
System.out.println("栈满! 入栈失败");
}
stack[top++] = object;
}
*/
//判空;
public boolean isEmpty(){
return size == 0;
}
//出栈;
public Object pop(){
//首先要判空;
if(isEmpty()){
throw new ArrayIndexOutOfBoundsException("不能为空");
}
Object o = stack[--size];
stack[size] = null;
return o;
}
/*
// 出栈
public Object pop() {
Object object = stack[--top];
stack[top] = null;
return object;
}
*/
/*
// 计算栈当前大小
public int size() {
return top;
}
// 判断是否是空栈
public boolean isEmpey() {
return top == 0;
}
// 判断是否栈满
public boolean isFull() {
return top >= size;
}
public Stack(int size) {
this.size = size;
}
*/
public static void main(String[] args) {
Stack stack = new Stack(3);
String[] data = new String[] { "a", "b", "c" };
for (int i = 0; i < data.length; i++) {
stack.push(data[i]);
System.out.println(data[i] + "");
}
System.out.println("***********");
while (!stack.isEmpty()) {
System.out.println(stack.pop() + "");
}
//}
}
}