栈的特点:先入后出

class ArrayStack {
    private int maxSize;
    private int[] stack;
    private int 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;
    }

    public void push(int value) {
        if (isFull()) {
            System.out.println("栈已满!");
            return;
        }
        top++;
        stack[top] = value;
    }
    public int pop() {
        if (isFull()) {
            System.out.println("栈空!");
            throw new RuntimeException("栈空");
        }
        int result = stack[top];
        top--;
        return result;
    }
    public void list() {
        if (isEmpty()) {
            System.out.println("栈空!");
        }
        while(!isEmpty()) {
            System.out.printf("%d,",stack[top]);
            top--;
        }
    }
}
posted on 2021-02-18 15:56  凸凸大军的一员  阅读(34)  评论(0编辑  收藏  举报