1. package com.atguigu.stack;
    2. import java.util.Scanner;
    3. /**
    4. * @author Dxkstart
    5. * @create 2021-10-07-18:41
    6. */
    7. public class ArrayStackDemo {
    8. public static void main(String[] args) {
    9. //测试ArrayStack
    10. //先创建一个ArrayStack对象 ---> 表示栈
    11. ArrayStack stack = new ArrayStack(5);
    12. int key = 0;
    13. Scanner scanner = new Scanner(System.in);
    14. boolean b = true;
    15. l:
    16. while (b) {
    17. System.out.println("1.显示栈的所有数据");
    18. System.out.println("2.添加数据");
    19. System.out.println("3.取出数据");
    20. System.out.println("4.退出程序");
    21. key = scanner.nextInt();
    22. switch (key) {
    23. case 1:
    24. try {
    25. stack.list();
    26. } catch (Exception e) {
    27. System.out.println(e.getMessage());
    28. }
    29. break;
    30. case 2:
    31. System.out.println("请输入一个数");
    32. stack.push(scanner.nextInt());
    33. break;
    34. case 3:
    35. try {
    36. int value = stack.pop();
    37. System.out.printf("出栈的数据是%d \n", value);
    38. } catch (Exception e) {
    39. System.out.println(e.getMessage());
    40. }
    41. break;
    42. case 4:
    43. scanner.close();
    44. System.out.println("再见~~~~");
    45. break l;
    46. }
    47. }
    48. }
    49. }
    50. //定义一个ArrayStack表示栈
    51. class ArrayStack {
    52. private int maxSize;//栈的大小
    53. private int[] stack;//数组,数组模拟栈,数据就放在该数组中
    54. private int top = -1;//top表示栈顶,初始化为-1
    55. //构造器
    56. //初始化栈
    57. public ArrayStack(int maxSize) {
    58. this.maxSize = maxSize;
    59. stack = new int[maxSize];
    60. }
    61. //栈满
    62. public boolean isFull() {
    63. return top == maxSize - 1;
    64. }
    65. //栈空
    66. public boolean isEmpty() {
    67. return top == -1;
    68. }
    69. //入栈 - push
    70. public void push(int value) {
    71. //先判断栈是否满
    72. if (isFull()) {
    73. System.out.println("栈满");
    74. return;
    75. }
    76. top++;
    77. stack[top] = value;
    78. }
    79. //出栈 - pop,将栈顶的数据返回
    80. public int pop() {
    81. //先判断是否为空
    82. if (isEmpty()) {
    83. //抛出异常
    84. throw new RuntimeException("栈空");
    85. }
    86. int value = stack[top];
    87. top--;
    88. return value;
    89. }
    90. //显示栈的所有数据【遍历栈】
    91. public void list() {
    92. //先判断是否为空
    93. if (isEmpty()) {
    94. //抛出异常
    95. throw new RuntimeException("栈空");
    96. }
    97. //需要从栈顶开始显示数据
    98. for (int i = top; i >= 0; i--) {
    99. System.out.printf("stack[%d] = %d \n", i, stack[i]);
    100. }
    101. }
    102. }