基于数组,实现动态扩容的顺序栈

实现代码:

public class DynamicCapacityArrayStack<T> {

    /**
     * 存放数据的数组
     */
    private T[] items;

    /**
     * 栈中元素初始化容量大小
     */
    public static int initSize = 10;

    /**
     * 当前栈中元素个数
     */
    private int currentSize;

    /**
     * 接收的对象类型
     */
    Class<T> type;

    public DynamicCapacityArrayStack(Class<T> type) {
        this(type, initSize);
    }

    /**
     * 初始化数组,申请一个大小为 initSize 的数组空间
     */
    public DynamicCapacityArrayStack(Class<T> type, int initSize) {
        DynamicCapacityArrayStack.initSize = initSize;
        this.items = (T[]) Array.newInstance(type, initSize);
        this.type = type;
    }

    /**
     * 入栈操作
     */
    public void push(T item) {
        if (currentSize + 1 == initSize) {
            T[] newArray = (T[]) Array.newInstance(type, initSize * 2);
            // 扩容后的初始化容量大小
            DynamicCapacityArrayStack.initSize = initSize * 2;
            int preserveLength = Math.min(currentSize, initSize);
            // 数组内容复制
            if (preserveLength > 0) {
                System.arraycopy(items, 0, newArray, 0, preserveLength);
            }
            // 将新的数组赋值给items
            items = newArray;
        }
        items[currentSize++] = item;
    }

    /**
     * 出栈操作
     */
    public T pop() {
        if (isEmpty()) {
            return null;
        }
        T outData = (T) items[--currentSize];
        return outData;
    }

    /**
     * 获取栈顶元素
     */
    public T peek() {
        if (isEmpty()) {
            return null;
        }
        T topData = (T) items[currentSize-1];
        return topData;
    }

    /**
     * 当前栈的长度
     */
    public int getSize() {
        return currentSize;
    }

    /**
     * 栈是否为空
     */
    public boolean isEmpty() {
        return currentSize == 0;
    }
}

测试示例:

public static void main(String[] args) {
        DynamicCapacityArrayStack<String> stack = new DynamicCapacityArrayStack(String.class, 2);
        stack.push("1");
        stack.push("2");
        stack.push("3");

        int size = stack.getSize();
        for (int i = 0; i < size; i++) {
            String pop = stack.pop();
            System.out.println(pop);
        }
        System.out.println(DynamicCapacityArrayStack.initSize);
    }

结果:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值