Java數據結構之堆棧-使用數組實現堆棧

public class TestStack {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
    Stack st=new Stack(8);
    st.push("new01");
    st.push("new02");
    st.push("new03");
    System.out.println(st.size());
    System.out.println(st.top());
	}

}

Java實現堆棧類

public class Stack {
private int capacity = 100;
private String[] items;
private int top=0;
public Stack(){
	this(100);
}
//
public Stack(int i) {
	// TODO Auto-generated constructor stub
	this.capacity=i;
	items=new String[i];
}
//入棧
public void push(String s){	
	top++;
	items[top]=s;
}
//出棧
public void pop(){
	items[top]=null;
	top--;
}

public void empty(){
	top=0;
}
public String top(){
	return items[top];
}
public int size(){
	return top;
}
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章