Java~栈的数组表示

来源:互联网 发布:多米诺激光机软件 编辑:程序博客网 时间:2024/05/11 11:01

/**
 * @author YuanZhenhui
 * @serialData 2006-9-10
 * @version 1.0
 *
 */

栈接口

public interface StackInterface {
 public boolean isEmpty();
 
 public boolean isFull();
 
public void push(Object oo) throws OverFlowException;
 
public Object pop()throws UnderFlowException;
 
 public Object get();
}

//自定义异常
class OverFlowException extends Exception{
 public OverFlowException(){
  System.out.println("this is an exception");
 }
}
class UnderFlowException extends Exception{
 public UnderFlowException(){
  
 }
}
public class MyStack implements StackInterface{
 private Object table[];
// top为栈顶元素
 private int top=-1;
// 构造n个存储单元的栈
 public MyStack(int n){
  table=new Object[n];
 }
 
 public boolean isEmpty(){
  return top==-1;
 }
 
 public boolean isFull(){
  return top>=table.length-1;
 }
 
 public void push(Object oo) throws OverFlowException{
  if(!this.isFull()){
   top++;
   table[top]=oo;
  }else{
   throw new OverFlowException();
  }
 }
 
 public Object pop()throws UnderFlowException{
  Object temp=null;
  if(!this.isEmpty()){
   temp=table[top];
   table[top]=null;
   top--;
  }else{
   throw new UnderFlowException();
  }
  return temp;
 }
 
 public Object get(){
  if(!this.isEmpty()){
   return table[top];
  }else
   return null;
 }
}