/** * @Author: Yeman * @Date: 2021-10-16-11:25 * @Description: */ public class ArrayStackTest { public static void main(String[] args) { ArrayStack arrayStack = new ArrayStack(5); arrayStack.push(3); arrayStack.push(9); arrayStack.push(22); arrayStack.show(); arrayStack.pop(); arrayStack.show(); } } class ArrayStack { private int maxSize; //栈的大小 private int[] stack; //数组模拟栈 private int top = -1; //栈顶,初始化-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; } //入栈 public void push(int value){ if (isFull()){ System.out.println("栈满,入栈失败!"); return; } top++; stack[top] = value; } //出栈 public int pop(){ if (isEmpty()){ throw new RuntimeException("栈空,出栈失败!"); } return stack[top--]; //先得到stack[top],然后top-- } //遍历(从栈顶向下) public void show(){ if (isEmpty()){ System.out.println("栈空!"); return; } for (int i = top; i >= 0; i--) { System.out.printf("stack[%d] = %d\n",i,stack[i]); } } }