import java.util.Scanner;
public class ArrayStackDemo {
public static void main(String[] args){
ArrayStack arrayStack=new ArrayStack(4);
Scanner s=new Scanner(System.in);
boolean flag=true;
while(flag){
System.out.println("1.给栈添加元素");
System.out.println("2.给栈弹出元素");
System.out.println("3.给栈显示元素");
System.out.println("4.退出");
System.out.print("请选择要执行功能的序号:");
int x=s.nextInt();
switch(x){
case 1:
System.out.println("请输入要添加的数字:");
int num=s.nextInt();
try{
arrayStack.pushStack(num);
System.out.println(num+"添加成功!");
}catch(RuntimeException e){
System.out.println(e.getMessage());
}
break;
case 2:
try{
int n=arrayStack.popStack();
System.out.println(n+"出栈成功!");
}catch(RuntimeException e){
System.out.println(e.getMessage());
}
break;
case 3:
arrayStack.showStack();
break;
case 4:
s.close();
flag=false;
System.out.println("当前程序已结束!");
break;
default:
System.out.println("请输入1-4有效选择数字!");
break;
}
}
}
}
class ArrayStack{
int Maxsize;
int top;
int[] stack;
public ArrayStack(int Maxsize){
this.Maxsize=Maxsize;
stack=new int[Maxsize];
top=-1;
}
public boolean isEmpty(){
return top==-1;
}
public boolean isFull(){
return top==Maxsize-1;
}
public void pushStack(int n){
if(isFull()){
throw new RuntimeException("栈已满!");
}
++top;
stack[top]=n;
}
public int popStack(){
if(isEmpty()){
throw new RuntimeException("栈为空!");
}
int value=stack[top];
top--;
return value;
}
public void showStack(){
if(isEmpty()){
System.out.println("当前栈为空!");
return;
}
//从栈顶打印输出栈
for(int i=top;i>=0;i--){
System.out.println(stack[i]+" ");
}
}
}
数组模拟栈
最新推荐文章于 2024-05-12 20:46:47 发布