[数据结构]ArrayStack

非常简单

package Example;


//用数组结构实现固定大小的栈

public class ArrayStack{
    private Integer[] arr;
    private Integer index;

    public ArrayStack(int initSize) throws Exception {
        if(initSize<0){
            throw new Exception("初始化大小必须大于0");
        }
        arr=new Integer[initSize];
        index=0;
    }

    public Integer peek(){
        if(index==0)
            return null;
        return arr[index-1];
    }

    public void push(int obj) throws Exception {
        if(index==arr.length){
            throw new Exception("栈满!");
        }
        arr[index++] = obj;
    }

    public Integer pop() throws Exception {
        if(index==0){
            throw new Exception("栈空!");
        }
        return arr[--index];
    }
}
posted @ 2020-02-24 22:21  KrisTse  阅读(124)  评论(0编辑  收藏  举报