zoukankan      html  css  js  c++  java
  • 基础的集合实现

    引用
    《算法4》1.3.2.5 迭代

    特点:小巧精妙

    • 自动扩缩容
    • 避免对象游离
    • 使用数组能够高效检索数据
    • 实现Iterable 对外提供 Iterator
    • Bag、Queue、Stack、List基本都可以依葫芦画瓢
    • 这是一个线程不安全的实现类
    import java.util.Iterator;
    
    public class ResizingArrayStack<Item> implements Iterable<Item> {
        private Item[] a = new (Item[]) new Object[1]; 	// 栈元素
        private int N = 0;								// 元素数量
        public boolean isEmpty() {return N == 0;}
        public int size() {return N;}
        
        private void resize(int max) {
            // 将栈移动到一个大小为max的新数组
            Item[] temp = (Item[]) new Object[max];
            for (int i=0; i<N; i++)
                temp[i] = a[i];
            a = temp;
        }
        
        public void push(Item item) {
            // 将元素添加到栈顶
            if (N == a.length) resize(2*a.length);
            a[N++] = item;
        }
        
        public Item pop() {
            // 从栈顶删除元素
            Item item = a[--N];
            //避免对象游离
            a[N] == null;	
            if (N > 0 && N == a.length/4) resize(a.length/2);
            return item;
        }
        
        public Iterator<Item> iterator() {return new ReverseArrayIterator();}
        
        public class ReverseArrayIterator implements Iterator<Item> {
            // 支持后进先出的迭代
            private int i = N;
            public boolean hashNext() {return i>0;};
            public Item next() {return a[--i];}
            public void remove() {}
        }
    }
    
  • 相关阅读:
    接口型模式
    spring-cloud-config安全问题
    适配器模式
    spring boot + quartz 集群
    LeetCode Weekly Contest 147
    LeetCode Weekly Contest 146
    LeetCode Weekly Contest 144
    LeetCode Weekly Contest 143
    LeetCode Weekly Contest 142
    LeetCode Weekly Contest 141
  • 原文地址:https://www.cnblogs.com/linma/p/13181425.html
Copyright © 2011-2022 走看看