首页 > 编程语言 > 详细

栈--数组实现

时间:2018-04-30 11:08:39      阅读:205      评论:0      收藏:0      [点我收藏+]
import java.util.Arrays;
import java.util.EmptyStackException;

public class ArrayStack<E> {

    protected Object[] elementData; //数组
    protected int elementCount; //元素个数
    protected int capacityIncrement; //扩容个数

    private static final long serialVersionUID = 1224463164541339165L;

    public ArrayStack(){}

    /**
     * 添加元素
     * @param item
     * @return
     */
    public E push(E item) {

        int minCapacity = elementCount+1;
        if (minCapacity - elementData.length > 0){
            //扩容

            int oldCapacity = elementData.length;
            int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                    capacityIncrement : oldCapacity);

            if (newCapacity - minCapacity < 0)
                newCapacity = minCapacity;
            elementData = Arrays.copyOf(elementData, newCapacity);
        }
        elementData[elementCount++] = item;

        return item;
    }

    /**
     * 删除元素
     * @return
     */
    public synchronized E pop() {
        E       obj;
        int     len = size();

        //拿到要删除的元素
        obj = peek();

        //做删除操作
        elementData[elementCount] = null;
        elementCount--;

        return obj;
    }

    public synchronized E peek() {
        //判断stack不为空
        int     len = size();
        if (len == 0)
            throw new EmptyStackException();

        int index = len -1;
        //防止数组下标越界
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
        }
        E       obj;
        obj= (E) elementData[index];
        return  obj;
    }


    /**
     * 长度
     * @return
     */
    public synchronized int size() {
        return elementCount;
    }

}

 

栈--数组实现

原文:https://www.cnblogs.com/inspred/p/8973018.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!