用Java实现栈结构

栈是一种先进后出的数据结构,出栈入栈都是操作的栈顶元素,下面是利用Java语言实现的一个简单的栈结构

class MyStack{
private int size;//栈大小
private Object[] elementData;//栈中元素
private int top;//栈顶指针

public MyStack(int size){
    this.size = size;
    this.top = 0;
    this.elementData = new Object[size];
}

public boolean push(Object o){
    if (ensureCapacity(top+1)){
        top++;
        elementData[top] = o;
        return true;
    }
    return false;
}

public Object pop(){
    if (top >= 0){
        Object o = elementData[top];
        elementData[top] = null;
        top--;
        return o;
    }
    return null;
}

public boolean isEmpty(){
    return top == 0;
}

private boolean ensureCapacity(int capacity) {
    if (capacity >= this.size){
        return false;
    }
    return true;
}

}
原文地址:https://www.cnblogs.com/canmeng-cn/p/8046143.html