public class MyStack {
String [] arr =new String[5];//栈的大小为5
int top = 0;//栈底指针为0
int length = 0; //元素个数初始值为0个
//入栈
public void push(String value){
if(top==arr.length){//判断栈是否已满
System.out.println("栈已满,无法继续存储...");
return;
}
arr[top++]=value;//入栈存储
length++;
}
//出栈
public String pop(){
if(empty()==true){//判断栈是否为空
System.out.println("空栈,无法继续操作!");
return null;
}
String value = arr[--top];
arr[top]=null;//出栈之后设置为null
length--;
return value;
}
//判断是否为空
public boolean empty(){
for(int i=0; i<arr.length; i++){
if(null!=arr[i]){
return false;
}
}
return true;
}
//清除栈中所有元素
public void clear(){
for(int i=0; i<arr.length; i++){
arr[i]=null;
}
top=0;//清空之后指针指向栈底
length=0;
}
//获取栈的元素个数
public int size(){
return length;
}
//测试该栈
public static void main(String[] args){
MyStack ms = new MyStack();
ms.push("hello");
ms.push("qswd");
ms.push("jjfvgnj");
ms.push("jdhe");
ms.push("dvkf");
System.out.println("存储的元素个数:"+ms.size());
String value = ms.pop();
System.out.println("出栈元素:"+value);
System.out.println("存储的元素个数:"+ms.size());
ms.clear();
System.out.println("存储的元素个数:"+ms.size());
ms.pop();
}
}
java模拟栈的实现
最新推荐文章于 2024-04-30 01:34:49 发布