栈的java实现

public class Stack {
    private int top = -1;
    private Object[] arr;

    public Stack(int capacity) throws Exception{
        if(capacity < 0){
            throw new Exception("Illegal capacity:" + capacity);
        }
        arr = new Object[capacity];
    }

    public void push(Object object) throws Exception{
        if(top == arr.length - 1){
            throw new Exception("Stack is full");
        }
        arr[++top] = object;
    }

    public Object pop() throws Exception{
        if(top == -1){
            throw new Exception("Stack is empty");
        }
        return arr[top--];
    }
}

 栈stack后进先出,用一个top元素进行控制标注最顶端


使用LinkedList的addFirst进行push

原文地址:https://www.cnblogs.com/zhangchiblog/p/8416962.html