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

/**
 * 使用数组实现固定大小的栈结构
 */
public class ArrayStack {
    private int[] data;
    private int index;

    public ArrayStack(int capacity){
        if (capacity < 0)
            throw new IllegalArgumentException("the capacity should not be less than 0");
        data = new int[capacity];
        index = 0;
    }

    public void push(int obj){
        if (index == data.length)
            throw new ArrayIndexOutOfBoundsException("the stack is full");
        data[index++] = obj;
    }

    public int pop(){
        if (index == 0)
            throw new ArrayIndexOutOfBoundsException("the stack is empty");
        return data[--index];
    }

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

全部评论

相关推荐

04-15 23:42
中山大学 Java
ResourceUtilization:过几天楼主就会捧着一堆offer来问牛友们该怎么选辣
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务