Java用数组实现栈

package ds;

public class MyArrayStack {
    private Object[] stack;
    private int size;
    private int topIndex;

    public MyArrayStack(int maxSize) {
        this.size = maxSize;
        stack = new Object[maxSize];
        this.topIndex = -1;
    }

    //判断栈是否为空
    public boolean isEmpty() {
        return (topIndex == -1);
    }

    //判断栈是否已满
    public boolean isFull() {
        return (topIndex == size - 1);
    }

    //入栈
    public void push(E e) {
        if (isFull()) {
            throw new IndexOutOfBoundsException("stack is full!");
        }
        stack[++topIndex] = e;
        size++;
    }

    //出栈 删除
    public E pop() {
        if (isEmpty()) {
            throw new RuntimeException("stack is full!");
        }
        E e = (E) stack[topIndex--];
        stack[topIndex--] = null;
        size--;
        return e;
    }

    //返回栈顶元素
    public E peep() {
        if (isEmpty()) {
            throw new RuntimeException("stack is full!");
        }
        return (E)stack[topIndex];
    }
}

 

你可能感兴趣的:(Java用数组实现栈)