栈的定义和简单:总结起来是:先进后出
作者在代码里做了详细注释,这里不在赘述;
/**
* 基于数组实现的顺序栈
*/
public class ArrayStack {
private String item[];//数组
private int count;//栈中元素的个数
private int n;//栈的大小
public ArrayStack(){}
public ArrayStack(int n){
this.item = new String[n];//申请一个为n 的数组空间
this.count=0;//
this.n=n;
}
//添加栈顶元素的方法
public boolean push(String item){
if(count==n) return false;//数组空间不够时,入栈失败
//将item 放到下标为count 的位置,并且count +1
this.item[count++]=item;
return true;
}
public String pop(){
if(count==0)return null;//若栈为空,直接返回空
//返回下标为count-1 的数组元素,并且栈中的元素个数 -1
String temp=item[count-1];
count--;
return temp;
}
}
实现类:
public class ArrayStackTest {
@Test
public void test(){
ArrayStack as=new ArrayStack(3);
as.push("1");
as.push("2");
as.push("3");
as.push("4");//栈满,添加不进去了
System.out.println(as.pop());
System.out.println( as.pop());
System.out.println(as.pop());
System.out.println(as.pop());//栈空,输出空
}
}
运行结果: