跳至主要內容

1.3 线性表-栈


public class MyStack<E> {

    private int size;
    private Object[] array;

    public MyStack() {
        // 默认创建长度是10的数组
        array = new Object[10];
        size = 0;
    }

    public MyStack(int capacity) {
        // 默认创建长度是10的数组
        array = new Object[capacity];
        size = 0;
    }

    public E peek() {
        if (size == 0) {
            return null;
        } else {
           return (E) array[size - 1];
        }
    }

    public E pop() {
        if (size == 0) {
            return null;
        } else {
            E item = (E) array[size - 1];
            size--;
            return item;
        }
    }

    public boolean push(E item) {
        int len = array.length;
        if (len == size) {
            Object[] ta = new Object[(int) (len * 1.5)];
            System.arraycopy(array, 0, ta, 0, size);
            array = ta;
        }
        array[size] = item;
        size++;
        return true;
    }

}

参考

https://www.cnblogs.com/54chensongxia/p/14104304.htmlopen in new window

上次编辑于: