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;
        }
    
    }
  • 相关阅读:
    moment.js获取当前日期是当年的第几周
    angulajs中引用chart.js做报表,修改线条样式
    moment算本月开始日期和结束日期
    TFS(Team Foundation Server)敏捷使用教程(四):工作项跟踪(1)
    个人微信收款回调通知
    Winform,Wpf快捷键
    RemindMe
    数组循环左移p位
    RemindMe 说明
    双网卡同时上内外网
  • 原文地址:https://www.cnblogs.com/inspred/p/8973018.html
Copyright © 2011-2022 走看看