大话数据结构—栈(四)

1.数组实现栈

public class ArrayStack {
    private Object[] data;
    private static final int MAX_SIZE = 10;
    private int top = -1;

    public ArrayStack() {
        this.data = new Object[MAX_SIZE];
    }

    public void push(Object element) {
        if (top == (MAX_SIZE - 1)) {
            throw new RuntimeException("栈满");
        }
        data[++top] = element;
    }

    public Object pop() {
        if (top == -1) {
            throw new RuntimeException("空栈");
        }
        return data[top--];
    }

    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack();
        stack.push(1);
        stack.push(2);
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());

    }
}

你可能感兴趣的:(大话数据结构—栈(四))