0
点赞
收藏
分享

微信扫一扫

创建一个栈容器类

Fifi的天马行空 2022-04-23 阅读 85
java
package com.bjsxt;

import java.util.Arrays;
import java.util.EmptyStackException;

/**
 * @Author:Dai
 * @Date:2022/4/23 自定义栈容器
 */
public class MyStack<E> {

    private Object[] arr;   //存放元素的物理结构

    private int stakeLength = 4;    //数组的默认长度

    private int size;   //记录栈容器的元素个数

    private int index = -1;  //操作数组下标位置的指针

    /**
     * 判断栈容器是否为空
     *
     * @return
     */
    public boolean empty() {
        return this.size == 0;
    }

    /**
     * 获取栈顶元素
     *
     * @return
     */
    public E pop() {
        //如果栈容器是null,则抛出异常
        if (index == -1) {
            throw new EmptyStackException();
        }
        //记录元素个数
        this.size--;
        //返回栈顶元素
        return (E) this.arr[index--];
    }

    /**
     * 向栈容器中添加元素
     *
     * @param item
     * @return
     */
    public E push(E item) {
        //初始化数组
        this.capacity();
        //向数组中添加元素
        this.arr[++index] = item;
        //记录元素个数
        this.size++;

        return item;
    }

    /**
     * 查看此堆栈顶部的对象,而不从堆栈中删除它。
     *
     * @return
     */
    public E peek() {
        if (index == -1) {
            throw new EmptyStackException();
        }
        return (E) this.arr[index--];
    }

    /**
     * 数组初始化或者以1.5倍容量对数组扩容
     */
    private void capacity() {
        //数组初始化
        if (this.arr == null) {
            this.arr = new Object[this.stakeLength];
        }
        //以1.5倍对数组扩容
        if (this.size - (this.stakeLength - 1) >= 0) {
            this.stakeLength = this.stakeLength + (this.stakeLength >> 1);
            this.arr = Arrays.copyOf(this.arr, this.stakeLength);
        }
    }
}
举报

相关推荐

0 条评论