怎样用数组实现栈
来源:优易学  2011-12-20 13:57:29   【优易学:中国教育考试门户网】   资料下载   IT书店
  用数组实现栈
  思想:
  interface ArrayPK{
  void push(Object obj);
  Object pop();
  boolean isEmpty();
  boolean isFull();
  int Size();
  }
  public class ArrayStack implements ArrayPK{
  public final static int DEFAULT_CAPACITY=100;
  private Object[] stack;
  private int top;
  public ArrayStack(){
  this(DEFAULT_CAPACITY);
  }
  public ArrayStack(int capacity){
  if(capacity<1)
  throw new IllegalArgumentException("capacity must be > 0");
  stack=new Object[capacity];
  top=-1;
  }
  public void push(Object obj){
  if(obj == null)
  throw new IllegalArgumentException("object is null");
  if(isFull())
  throw new IllegalArgumentException("stack is full");
  stack[++top]=obj;
  }
  public Object pop(){
  if(isEmpty())
  throw new IllegalArgumentException("stack is empty");
  return stack[top--];
  }
  public boolean isEmpty(){
  if(top<0)
  return true;
  else
  return false;
  }
  public boolean isFull(){
  if(top+1==Size())
  return true;
  else
  return false;
  }
  public int Size(){
  return stack.length;
  }
  public static void main(String[] args){
  Object[] arr=new String[]{"liangming","gaojie","liangbing","wuxia","zhangjun"};
  ArrayStack as=new ArrayStack(20);
  for(int i=0;i<arr.length;i++){
  as.push(arr[i]);
  }
  while(!as.isEmpty()){
  System.out.println(as.pop());
  }
  }
  }

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训