【数据结构】数组实现栈

/**
 * 用数组实现栈结构
 * @author : wangtb
 * @date : 2019-10-04 22:50
 */
public class Array2Stack {

    private Integer[] arr;
    private Integer index;

    public Array2Stack(int initSize) {
        if (initSize < 0) {
            throw new IllegalArgumentException("The init index is less than 0");
        }
        arr = new Integer[initSize];
        index = 0;
    }

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

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

    public Integer pop() {
        if (index == 0) {
            throw new ArrayIndexOutOfBoundsException("The queue is empty");
        }
        return arr[--index];
    }
}

 

posted @ 2019-10-04 23:24  abs_征召不老  阅读(85)  评论(0)    收藏  举报