zoukankan      html  css  js  c++  java
  • 栈--数组实现

    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;
        }
    
    }
  • 相关阅读:
    python-json序列化和反序列化
    python-列表元祖字典集合、字符、字符串、函数处理
    Nmon监控服务端性能
    python-使用qq邮箱向163邮箱发送邮件、附件
    测试结论
    性能术语
    测试点-app、web、异常
    提测标准
    深度优先搜索的演示学习法——BlackBlank平台应用教学案例
    【赛后补题】ccpc2107秦皇岛H题
  • 原文地址:https://www.cnblogs.com/inspred/p/8973018.html
Copyright © 2011-2022 走看看