用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;
}

}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM