1. //数组模拟栈
    2. @Data
    3. public class ArrayStack {
    4. private int maxSize; //栈的大小
    5. private int[] stack; //模拟栈;存储数据
    6. private int top = -1; //模拟栈顶
    7. //初始化方法
    8. public ArrayStack(int maxSize) {
    9. this.maxSize = maxSize;
    10. stack = new int[maxSize];
    11. }
    12. //栈满
    13. public boolean isFull(){
    14. return maxSize-1 == top;
    15. }
    16. //栈空
    17. public boolean isNull(){
    18. return top == -1;
    19. }
    20. //入栈
    21. public void push(int value){
    22. if(isFull()){
    23. System.out.println("栈满了");
    24. return;
    25. }else{
    26. top++;
    27. stack[top] = value;
    28. }
    29. }
    30. //出站
    31. public int pop(){
    32. if(isNull()){
    33. throw new RuntimeException("暂无数据");
    34. }else {
    35. int i = stack[top];
    36. top--;
    37. return i;
    38. }
    39. }
    40. //遍历
    41. public void view(){
    42. if(isNull()){
    43. throw new RuntimeException("暂无数据");
    44. }else {
    45. for (int i = top; i >=0; i--) {
    46. System.out.println(stack[i]);
    47. }
    48. }
    49. }
    50. }
    1. public class Test {
    2. public static void main(String[] args) {
    3. ArrayStack arrayStack = new ArrayStack(3);
    4. arrayStack.push(1);
    5. arrayStack.push(2);
    6. arrayStack.push(3);
    7. arrayStack.pop();
    8. arrayStack.pop();
    9. arrayStack.pop();
    10. arrayStack.pop();
    11. arrayStack.view();
    12. }
    13. }