import java.util.Scanner;
public class ArrayStackDemo {
public static void main(String[] args) {
//测试ArrayStack是否正确
Scanner sca = new Scanner(System.in);
ArrayStack stack = new ArrayStack(10);
String key = "";
boolean loop = true;
while(loop) {
System.out.println("show : 显示栈");
System.out.println("exit : 退出");
System.out.println("push : 添加数据");
System.out.println("pop : 取出数据");
System.out.println("请输入指令");
key = sca.nextLine();
switch(key) {
case "show":
stack.list();
break;
case "push":
System.out.println("请输入数据:");
int data = sca.nextInt();
stack.push(data);
break;
case "pop":
try {
int res = stack.pop();
System.out.println("取出的数据是:"+res);
}catch(Exception e) {
}
break;
case "exit":
loop = false;
break;
default:
break;
}
}
sca.close();
}
}
//定义一个ArrayStack 表示栈
class ArrayStack{
private int maxSize;//栈的大小
private int[] stack;//数组,数组模拟栈
private int top = -1;
//构造器
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
stack = new int[this.maxSize];
}
//栈满
public boolean isFull() {
return top == maxSize-1;
}
//栈空
public boolean isEmpty() {
return top == -1;
}
//入栈--push
public void push(int data) {
if(isFull()) {
System.out.println("栈满");
return;
}
top++;
stack[top] = data;
}
//出栈-pop
public int pop() {
if(isEmpty()) {
//抛出异常
throw new RuntimeException("栈空,没有数据~");
}
int value = stack[top];
top--;
return value;
}
//遍历栈
public void list() {
if(isEmpty()) {
System.out.println("栈空,没有数据");
}
for(int i = top;i>=0;i--) {
System.out.printf("stack[%d] = %d\n", i,stack[i]);
}
}
}