0001 /* 0002 * 借助定长数组实现Stack接口 0003 */ 0004 0005 package dsa; 0006 0007 public class Stack_Array implements Stack { 0008 public static final int CAPACITY = 1024;//数组的默认容量 0009 protected int capacity;//数组的实际容量 0010 protected Object[] S;//对象数组 0011 protected int top = -1;//栈顶元素的位置 0012 0013 //按默认容量创建栈对象 0014 public Stack_Array() 0015 { this(CAPACITY); } 0016 0017 //按指定容量创建栈对象 0018 public Stack_Array(int cap) { 0019 capacity = cap; 0020 S = new Object[capacity]; 0021 } 0022 0023 //获取栈当前的规模 0024 public int getSize() 0025 { return (top + 1); } 0026 0027 //测试栈是否为空 0028 public boolean isEmpty() 0029 { return (top < 0); } 0030 0031 //入栈 0032 public void push(Object obj) throws ExceptionStackFull { 0033 if (getSize() == capacity) 0034 throw new ExceptionStackFull("意外:栈溢出"); 0035 S[++top] = obj; 0036 } 0037 0038 //取栈顶元素 0039 public Object top() throws ExceptionStackEmpty { 0040 if (isEmpty()) 0041 throw new ExceptionStackEmpty("意外:栈空"); 0042 return S[top]; 0043 } 0044 0045 //出栈 0046 public Object pop() throws ExceptionStackEmpty { 0047 Object elem; 0048 if (isEmpty()) 0049 throw new ExceptionStackEmpty("意外:栈空"); 0050 elem = S[top]; 0051 S[top--] = null; 0052 return elem; 0053 } 0054 }