package com.atguigu.stack;
import java.util.Scanner;
/**
* @author Dxkstart
* @create 2021-10-07-18:41
*/
public class ArrayStackDemo {
public static void main(String[] args) {
//测试ArrayStack
//先创建一个ArrayStack对象 ---> 表示栈
ArrayStack stack = new ArrayStack(5);
int key = 0;
Scanner scanner = new Scanner(System.in);
boolean b = true;
l:
while (b) {
System.out.println("1.显示栈的所有数据");
System.out.println("2.添加数据");
System.out.println("3.取出数据");
System.out.println("4.退出程序");
key = scanner.nextInt();
switch (key) {
case 1:
try {
stack.list();
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 2:
System.out.println("请输入一个数");
stack.push(scanner.nextInt());
break;
case 3:
try {
int value = stack.pop();
System.out.printf("出栈的数据是%d \n", value);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 4:
scanner.close();
System.out.println("再见~~~~");
break l;
}
}
}
}
//定义一个ArrayStack表示栈
class ArrayStack {
private int maxSize;//栈的大小
private int[] stack;//数组,数组模拟栈,数据就放在该数组中
private int top = -1;//top表示栈顶,初始化为-1
//构造器
//初始化栈
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
stack = new int[maxSize];
}
//栈满
public boolean isFull() {
return top == maxSize - 1;
}
//栈空
public boolean isEmpty() {
return top == -1;
}
//入栈 - push
public void push(int value) {
//先判断栈是否满
if (isFull()) {
System.out.println("栈满");
return;
}
top++;
stack[top] = value;
}
//出栈 - pop,将栈顶的数据返回
public int pop() {
//先判断是否为空
if (isEmpty()) {
//抛出异常
throw new RuntimeException("栈空");
}
int value = stack[top];
top--;
return value;
}
//显示栈的所有数据【遍历栈】
public void list() {
//先判断是否为空
if (isEmpty()) {
//抛出异常
throw new RuntimeException("栈空");
}
//需要从栈顶开始显示数据
for (int i = top; i >= 0; i--) {
System.out.printf("stack[%d] = %d \n", i, stack[i]);
}
}
}