1、栈的实现类Stack的代码如下所示:
public class Stack { private Object[] array;//存放栈元素的数组 private int capacity;//栈的容量 private int top;//栈顶元素的索引 public Stack(){ } public Stack(int capacity){ create(capacity); } //创建栈 public void create(int capacity){ array = new Object[capacity]; this.capacity = capacity; this.top = 0; } //入栈 public boolean push(Object data){ boolean ret = (array != null) && (data != null) && (top < capacity); if(ret){ array[top++] = data; } return ret; } //出栈 public Object pop(){ Object ret = null; if((array != null) && (top > 0) && (top <= capacity)){ ret = array[--top]; } return ret; } //栈的容量 public int getCapacity(){ return capacity; } //栈中的元素个数 public int getCount(){ return top; } //栈是否为空 public boolean isEmpty(){ return top == 0; } }
2、测试类Test的实现代码如下所示:
public class Test { public static void main(String[] args) { Stack stack = new Stack(); stack.create(5); stack.push("元素1"); stack.push("元素2"); stack.push("元素3"); System.out.println("栈的容量:"+stack.getCapacity()); System.out.println("元素个数:"+stack.getCount()); System.out.println("栈是否为空?"+stack.isEmpty()); System.out.println("\n栈中的所有元素:"); while(!stack.isEmpty()){ System.out.print(stack.pop()+" "); } } }