棧是一種先進后出的數據結構,出棧入棧都是操作的棧頂元素,下面是利用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;
}
}