import java.util.Scanner;
public class StackArrayDemo {
public static void main(String[] args) {
//创建StackArray对象
StackArray stackArray = new StackArray(4);
Scanner scanner = new Scanner(System.in);
boolean loop = true;
String key = "";
while (loop){
System.out.println("show");
System.out.println("exit");
System.out.println("push");
System.out.println("pop");
System.out.println("请输入菜单: ");
key = scanner.next();
switch (key){
case "show":
stackArray.list();
break;
case "exit":
loop = false;
break;
case "push":
System.out.println("请输入一个数: ");
int data = scanner.nextInt();
stackArray.push(data);
break;
case "pop":
int res = stackArray.pop();
System.out.println("出栈的数据是: "+res);
break;
}
}
}
}
class StackArray{
private int maxSize; //栈的大小
private int top = -1;
private int [] stack;//数组模拟栈,数据就放在该数组
//构造器
public StackArray(int maxSize) {
this.maxSize = maxSize;
stack = new int[maxSize] ;
}
//判断栈满
public boolean isFull(){
return top == maxSize -1;
}
//判断栈空
public boolean isEmpty(){
return top == -1;
}
//入栈
public void push(int value){
//往里面加东西是判满,从里面拿东西是判空
if (isFull()) {
System.out.println("栈满");
return;
}
top ++;
stack[top] = value;
}
//出栈
public int pop(){
//判空
if (isEmpty()){
System.out.println("栈空");
return 0;
}
int data = stack[top];
top --;
return data;
}
//遍历栈 遍历时需要从栈顶开始显示数据
public void list(){
//判空
if (isEmpty()){
System.out.println("栈空");
return ;
}
for (int i = top; i >= 0 ; i --) {
System.out.printf("stack[%d] = %d\n",i,stack[i]);
}
}
}
用数组模拟栈
最新推荐文章于 2022-05-29 20:45:49 发布