package DataStructure;
import java.util.Scanner;
/**
* Created with IntelliJ IDEA.
* Description:
* User: 86178
* Date: 2024-02-13
* Time: 18:12
*/
public class StackDemo {
public static void main(String[] args) {
MyStack st=new MyStack(5);
boolean loop=true;
Scanner scanner=new Scanner(System.in);
while(loop){
System.out.println("exit退出程序");
System.out.println("show显示栈的信息");
System.out.println("push入栈");
System.out.println("pop弹栈");
String key=scanner.next();
switch(key){
case "show":
st.show();
break;
case "push":
System.out.println("请输入您需要入栈的元素");
int n=scanner.nextInt();
st.Push(n);
break;
case "pop":
st.Pop();
break;
case "exit":
loop=false;
System.out.println("退出程序");
break;
}
}
}
}
class MyStack{
private int top;//栈顶
private int[] StArr;//数组
private int maxSize;//栈的大小
public MyStack(int max){
maxSize=max;
StArr=new int[max];
top=-1;
}
public boolean isEmpty(){
return top==-1;//当top=-1 为空
}
public boolean isFull(){
return top==maxSize-1;
}
//todo 入栈
public void Push(int n){
if(isFull()){
System.out.println("栈满");
return;
}else {
StArr[++top]=n;
}
}
//todo 出栈
public void Pop(){
if(isEmpty()) throw new RuntimeException("栈空");
else{
StArr[top]=0;
top--;
}
}
//todo 返回栈顶元素
public int Top(){
if(isEmpty()) throw new RuntimeException("栈空");
else{
return StArr[top];
}
}
//todo 打印栈的信息
public void show(){
if(isEmpty()){
System.out.println("栈空");
return;
}
System.out.println("-----------------------");
System.out.println("top="+top);
System.out.println("打印栈");
for(int i=top;i>=0;i--){
System.out.print(StArr[i]+" ");
}
System.out.println();
System.out.println("-----------------------");
}
}
尚硅谷Java数据结构--数组模拟栈
于 2024-02-13 18:41:05 首次发布