用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