栈的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

 

posted on 2018-02-05 11:49  张小泽的小号  阅读(102)  评论(0编辑  收藏  举报

导航