public class Do {
private int arr[]; //存储栈中的元素
private int length=5;//整型数组的长度
private int size;//栈中实际元素的个数
public Do(){ //默认的构造函数
arr=new int[length];
}
public Do(int initlength){
if(initlength>length){
this.length=initlength;
}
arr=new int[length];
}
public void push(int i){ //进栈
if(size==length){
System.out.println("栈已满");
return;
}
if(i==0){
System.out.println("不能存储默认值0");
return;
}
arr[size]=i;
size++;
}
public int pop(){ //出栈
if(size==0){
System.out.println("栈已空");
return 0;
}
int temp=arr[size-1];
arr[size-1]=0; //将出栈的元素在栈中的值改为0
size--;
return temp;
}
public void clean(){ //清除占中的所有元素
for(int i=0;i<this.size;i++){
arr[i]=0;
}
this.size=0;
}
public int getSize(){
return this.size;
}
}
测试类:
public class Zhan {
public static void main(String []args){
Do stack =new Do();
stack.push(55);
stack.push(66);
stack.push(77);
System.out.println("栈中元素为:"+stack.getSize());
stack.push(88);
stack.push(99);
stack.push(45);
stack.clean();
System.out.println("栈中元素为:"+stack.getSize());
stack.push(55);
stack.push(66);
stack.push(77);
stack.pop();
stack.pop();
System.out.println("栈中元素为:"+stack.getSize());
stack.pop();
stack.pop();
}
}