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



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