数据结构与算法之LinkedList源码分析

Java语言实现数据结构与算法全解(含完整源代码) 很多人以为 Java 的ArrayList是每次扩容一倍,其实不然!JDK 中采用的是1.5 倍增长策略,具体实现如下:// 相当于 *1.5这里用了位运算>> 1来代替除以 2,既高效又巧妙。那问题来了:为什么不干脆翻倍呢?难道不是越大越好吗?答案是——平衡的艺术 🎯。扩容方式内存利用率复制频率总体重写成本固定增量(+k)高高O(n²)翻倍扩容(×2)低(最多浪费 50%)低O(n) 阅读详情

1 LinkedList的基本结构

链表就和链子一样,每一环都要连接着后边的一环和前边的一环,这样,当我们需要找这根链子的某一环的时候,只要我们能找到链子的任意一环,都可以找到我们需要的那一环。如下图:
  LinkedList在jdk1.6中的结构:
这里写图片描述
  LinkedList在jdk1.7中的结构:
这里写图片描述
  图片来源于:Java进阶之----LinkedList源码分析
  对比一下,知道区别在哪里了吧?在1.7中,去掉了环形结构,自然在代码中的也会有部分的改变。

2 LinkedList的基本结构

2.1 成员变量

//容器的size,存放当前链表有多少个节点
transient int size = 0;
//指向链表的第一个节点的引用
transient Node<E> first;
//指向链表的最后一个节点的引用
transient Node<E> last;

2.2 构造函数

public LinkedList() {
}

public LinkedList(Collection<? extends E> c) {
    this();
    addAll(c);
}

2.3 Node节点,LinkedList的内部私有类

private static class Node<E> {
    E item;//存储的数据
    Node<E> next;//指向链表的下一个数据
    Node<E> prev;//链表的前一个数据

    Node(Node<E> prev, E element, Node<E> next) {
        this.item = element;
        this.next = next;
        this.prev = prev;
    }
}

3 主要方法分析

3.1 add()系列方法分析

3.1.1 准备—核心的元素插入方法
//将数据作为FirstNode插入链表
private void linkFirst(E e) {
    //取得链表第一个元素
    final Node<E> f = first;
    //新建一个Node对象,该对象中数据为要插入的新数据
    //该数据的前一个节点为null(它是首个节点),后一个节点是之前的first节点
    final Node<E> newNode = new Node<>(null, e, f);
    //将新元素赋值为第一个元素
    first = newNode;
    if (f == null)
        //如果之前的首个节点(现在应该是第二个)为空,说明执行该插入操作前链表为空
        //新节点既是首节点,也是尾节点(因为现在链表元素size = 1)
        last = newNode;
    else
        //否则说明之前不是空链表
        f.prev = newNode;
    size++;
    modCount++;
}
//将数据作为LastNode插入链表
void linkLast(E e) {
    final Node<E> l = last;
    final Node<E> newNode = new Node<>(l, e, null);
    last = newNode;
    if (l == null)
        first = newNode;
    else
        l.next = newNode;
    size++;
    modCount++;
}
//将数据插入到某个链表节点之前
 void linkBefore(E e, Node<E> succ) {
    // assert succ != null;
    final Node<E> pred = succ.prev;
    final Node<E> newNode = new Node<>(pred, e, succ);
    succ.prev = newNode;
    if (pred == null)
        first = newNode;
    else
        pred.next = newNode;
    size++;
    modCount++;
}
3.1.2 理解任意一个核心方法,剩下两个方法也就不难理解了,以linkBefore为例

步骤1:执行linkBefore时,LinkedList的数据结构
这里写图片描述
步骤2:执行final Node newNode = new Node<>(pred, e, succ);
这里写图片描述
步骤3:执行pred.next = newNode;
这里写图片描述

3.1.3 add()方法分析
public boolean add(E e) {
    //其实只是执行linkLast方法将数据添加到链表末尾
    linkLast(e);
    return true;
}
public void add(int index, E element) {
    checkPositionIndex(index);
    if (index == size)
        // 链表为空时,index = size = 0
        linkLast(element);
    else
        linkBefore(element, node(index));
}
//将Collection中元素插入LinkedList最后
public boolean addAll(Collection<? extends E> c) {
    return addAll(size, c);
}

public boolean addAll(int index, Collection<? extends E> c) {
    // 检查传入的索引值是否在合理范围内
    checkPositionIndex(index);
    // 将给定的Collection对象转为Object数组
    Object[] a = c.toArray();
    int numNew = a.length;
    // 数组为空的话,直接返回false
    if (numNew == 0)
        return false;
    // 1.获取到插入位置
    Node<E> pred, succ;
    if (index == size) {
        // 链表为空时,index = size = 0
        succ = null;//succ: 索引位置从指定集合插入的第一个元素
        pred = last;//pred: 插入数组的第一个元素节点
    } else {
        // 链表非空时调用,node方法返回给定索引位置的节点对象
        succ = node(index);
        pred = succ.prev;
    }
    // 2.遍历数组,将数组的对象插入到节点中
    for (Object o : a) {
        @SuppressWarnings("unchecked") E e = (E) o;
        Node<E> newNode = new Node<>(pred, e, );
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode;
        pred = newNode;
    }
    // 3.将断开的部分连接上
    if (succ == null) {
        last = pred; // 将当前链表最后一个节点赋值给last
    } else {
        // 链表非空时,将断开的部分连接上
        pred.next = succ;
        succ.prev = pred;
    }
    // 记录当前节点个数
    size += numNew;
    modCount++;
    return true;
}
public void addFirst(E e) {
    linkFirst(e);
}

public void addLast(E e) {
    linkLast(e);
}

3.2 remove系列方法分析

3.2.1 准备—remove相关的核心方法
//删除第一个节点
private E unlinkFirst(Node<E> f) {
    final E element = f.item;
    final Node<E> next = f.next;
    f.item = null;
    f.next = null; // help GC
    first = next;
    if (next == null)
        last = null;
    else
        next.prev = null;
    size--;
    modCount++;
    return element;
}
//删除last节点
private E unlinkLast(Node<E> l) {
    final E element = l.item;
    final Node<E> prev = l.prev;
    l.item = null;
    l.prev = null; // help GC
    last = prev;
    if (prev == null)
        first = null;
    else
        prev.next = null;
    size--;
    modCount++;
    return element;
}
//删除某个节点
E unlink(Node<E> x) {
    // 临时保存移除对象的所有数据(prev和next指针以及存储数据)
    final E element = x.item;
    final Node<E> next = x.next;
    final Node<E> prev = x.prev;
    //prev指针为null,则说明该对象为头节点
    if (prev == null) {
        first = next;
    } else {
        prev.next = next;
        x.prev = null;
    }
    //next指针为null,则说明该对象为尾节点
    if (next == null) {
        last = prev;
    } else {
        next.prev = prev;
        x.next = null;
    }

    x.item = null;
    size--;
    modCount++;
    return element;
}
3.2.2 理解任意一个核心方法,剩下两个方法也就不难理解了,unlink(Node x)为例

(1)步骤1:执行remove操作前的数据结构
这里写图片描述
步骤2:执行prev指针相关
这里写图片描述
步骤3:执行next指针相关
这里写图片描述

3.2.3 remove代码分析
//按index删除节点很简单,node方法获取到对应的元素,然后unlink删除即可
public E remove(int index) {
    checkElementIndex(index);
    return unlink(node(index));
}
//按对象删除,依次遍历链表,然后找到首个符合的元素,然后删除该元素
public boolean remove(Object o) {
    if (o == null) {
        for (Node<E> x = first; x != null; x = x.next) {
            if (x.item == null) {
                unlink(x);
                return true;
            }
        }
    } else {
        for (Node<E> x = first; x != null; x = x.next) {
            if (o.equals(x.item)) {
                unlink(x);
                return true;
            }
        }
    }
    return false;
}

//同样没啥好说的,移除第一个Node
public E removeFirst() {
    final Node<E> f = first;
    if (f == null)
        throw new NoSuchElementException();
    return unlinkFirst(f);
}
//移除最后一个Node
public E removeLast() {
    final Node<E> l = last;
    if (l == null)
        throw new NoSuchElementException();
    return unlinkLast(l);
}
3.2.4 node(int index)–找到对应index的元素节点

类似于二分查找法,第一次查找根据index判断是从头部还是尾部获取对应元素,相对于数组结构,性能还是有所欠缺。

Node<E> node(int index) {
    if (index < (size >> 1)) {
        Node<E> x = first;
        for (int i = 0; i < index; i++)
            x = x.next;
        return x;
    } else {
        Node<E> x = last;
        for (int i = size - 1; i > index; i--)
            x = x.prev;
        return x;
    }
}

3.3 get方法分析

3.3.1 getFirst/getLast方法
public E getFirst() {  
    final Node<E> f = first;  
    if (f == )  
        throw new NoSuchElementException();  
    return f.item;  
}  
  
public E getLast() {  
    final Node<E> l = last;  
    if (l == )  
        throw new NoSuchElementException();  
    return l.item;  
}  
3.3.2 get方法
public E get(int index) {  
    // 校验给定的索引值是否在合理范围内  
    checkElementIndex(index);  
    return node(index).item;  
}  

4 LinkedList的其他实现

4.1 队列的方法—Queue

 /**
      * Retrieves, but does not remove, the head (first element) of this list.
     * @return the head of this list, or {@code null} if this list is empty
     */
    public E peek() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
    }

    /**
     * Retrieves, but does not remove, the head (first element) of this list.
     * @return the head of this list
     */
    public E element() {
        return getFirst();
    }
    /**
     * Retrieves and removes the head (first element) of this list.
     * @return the head of this list, or {@code null} if this list is empty
     */
    public E poll() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }
    /**
     * Retrieves and removes the head (first element) of this list.
     * @return the head of this list
     */
    public E remove() {
        return removeFirst();
    }
    /**
     * Adds the specified element as the tail (last element) of this list.
     */
    public boolean offer(E e) {
        return add(e);
    }

4.2 双端队列—Deque

public boolean offer(E e) {
        throw new RuntimeException("Stub!");
    }
    public boolean offerFirst(E e) {
        throw new RuntimeException("Stub!");
    }
    public boolean offerLast(E e) {
        throw new RuntimeException("Stub!");
    }
    public E peekFirst() {
        throw new RuntimeException("Stub!");
    }
    public E peekLast() {
        throw new RuntimeException("Stub!");
    }
    public E pollFirst() {
        throw new RuntimeException("Stub!");
    }
    public E pollLast() {
        throw new RuntimeException("Stub!");
    }

4.3 栈的方法

public void push(E e) {
        throw new RuntimeException("Stub!");
    }
    public E pop() {
        throw new RuntimeException("Stub!");
    }

5 实现例子

(1)采用链表实现的,因此在进行insert和remove动作时在效率上要比ArrayList要好得多,适合用来实现Stack(堆栈:先进后出)与Queue(队列:先进先出)。

public class StringStack {  
    private LinkedList<String> linkedList   
    = new LinkedList<String>();  
    /** 
     * 将元素加入LinkedList容器 (即插入到链表的第一个位置) 
     */  
    public void push(String name){  
        linkedList.addFirst(name);  
    }  
    /** 
     * 取出堆栈中最上面的元素  (即取出链表linkedList的第一个元素) 
     * @return 
     */  
    public String getTop(){  
        return linkedList.getFirst();  
    }  
    /** 
     * 取出并删除最上面的元素  (即移出linkedList的第一个元素) 
     * @return 
     */  
    public String pop(){  
        return linkedList.removeFirst();  
    }  
    /** 
     * 获取元素个数 
     */  
    public int size(){  
        return linkedList.size();  
    }  
    /** 
     * 判断堆栈是否为空 (即判断 linkedList是否为空) 
     * @return 
     */  
    public boolean isEmpty(){  
        return linkedList.isEmpty();  
    }  
    //测试  
    public static void main(String[] args) {  
        StringStack stack = new StringStack();  
        stack.push("yulon");  
        stack.push("xiaoyun");  
        stack.push("羽龙共舞");  
        System.out.print("第一个元素是:\t");  
        System.out.println(stack.getTop());  
        System.out.println();  
        System.out.println("全部元素:");  
        while(!stack.isEmpty()){  
            System.out.println("\t"+stack.pop());  
        }  
    }  
}  
第一个元素是: 羽龙共舞  
  
全部元素:  
    羽龙共舞  
    xiaoyun  
    yulon  

(2)如果要使用队列的功能,由于LinkedList也实现了java.util.Queue接口,所以可以直接使用LinkedList的实例来实现。

public class QueueDemo {  
    public static void main(String[] args) {  
        //父类引用queue指向子类对象  
        Queue<String> queue = new LinkedList<String>();  
        //offer()方法是往队列加入元素  
        queue.offer("xiaoyun");  
        queue.offer("yulon");  
        queue.offer("羽龙共舞");  
        String element = ;  
        while((element=queue.poll())!=){  
            System.out.println(element+"\t");  
        }  
    }  
}  
xiaoyun   
yulon     
羽龙共舞 

6 总结

6.1 优点

(1)LinkedList没有大小限制
(2)没有浪费存储空间(Node节点的创建需要额外消耗少量空间)
(3)add,remove等操作的空间消耗是固定的,不会造成对元素进行额外的移动拷贝

6.2 缺点

(1)除了对首尾元素外,对其他节点,进行add,remove,set,get等操作,都需要进行遍历查找的,时间复杂度为O(n)。

6.3 应用场景

(1)查询操作少,存储大量数据,可以考虑使用LinkedList。

6.4 多线程下

(1)LinkedList和ArrayList一样,都不是线程安全的。
(2)在考虑线程安全的情况下,可以使用 ConcurrentLinkedQueue代替LinkedList,直接同步LinkedList对象,或者使用List list = Collections.synchronizedList(new LinkedList(…));

7 对比ArrayList

7.1 相同点

(1)两者均不是线程安全的。
(2)两者都支持null值。
(3)都实现了List接口。

7.2 不同点

(1)ArrayList是实现了基于动态数组的数据结构,LinkedList基于链表的数据结构。
(2)对于随机访问get和set,ArrayList优于LinkedList,因为LinkedList要移动指针遍历查找。
(3)对于新增和删除操作add和remove,LinedList比较占优势,因为ArrayList要移动数据。

7.3 演示

这里写图片描述
  集合中装5万条数据,测试运行结果如上。因此,ArrayList更适合读取数据,linkedList更多的时候添加或删除数据。

7.4 原理

(1)ArrayList内部是使用可増长数组实现的,所以是用get和set方法是花费常数时间的,但是如果插入元素和删除元素,除非插入和删除的位置都在表末尾,否则代码开销会很大,因为里面需要数组的移动。
(2)LinkedList是使用双链表实现的,所以get会非常消耗资源,除非位置离头部很近。但是插入和删除元素花费常数时间。

8 参考链接

源码链接
Java8 LinkedList源码分析
Java进阶之----LinkedList源码分析
深入理解ArrayList与LinkedList的区别

Win10电脑的微软应用商店打不开怎么解决? 中自带的微软应用商店可以说是非常的好用,许多用户在使用的时候经常却发现自己电脑中自带的微软应用商店根本就打不开,这要怎么解决呢?下面小编就带着大家一起来看看吧!1、打开我们的电脑,在键盘上按下Windows+R打开运行窗口,输入“services.msc”然后按下回车键,打开服务页面。完成后,重新启动即可。4、键盘上按下Win+X组合键,在弹出的菜单里点击“命令提示符(管理员)”选项,打开命令提示符。3、再次打开运行窗口,在输入框里输入“wsreset”后按下回车键,刷新微软应用商店。 阅读详情

相关推荐

用51单片机和LD3320语音模块DIY一个会说话的温度报警器(附完整代码)

本文详细介绍了如何使用51单片机和LD3320语音模块DIY一个智能温度报警器,包括硬件选型、电路设计、软件开发及核心功能实现。通过DS18B20温度传感器和语音模块的结合,实现温度超标时的语音报警功能,适合智能家居系统等应用场景。附完整代码,方便开发者快速复现。

weixin_42525632的博客 425

list的add(int index,E e)用法踩坑分析以及【解决+分析】list集合循环添加对象被覆盖问题

add(int index ,E e)用法分析 事情的开始是打算for循环list存数据 但是到最后数据取出的总是最后存进去的那个,前面的数据都被覆盖了。 就看到了add(int index ,E e)方法,想着通过index一个索引插入一个数据,肯定就没有毛病了。但是并没有想象的那么顺利。 在用add(int index ,E e)方法时,后台会报错 java.lang.IndexOutOfBoundsException: Index: 1, Size: 0 索引的值超出了list的size,原本的概念

weixin_43902063的博客 4095

矩阵LED和矩阵按键

先说矩阵LED,如图: 下面以行几、列几的表达方法说明 三极管可以当做开关使用 由图可知,如果想让一个LED亮,那么它对应的行和列的三极管都要导通。如果这个矩阵每次只亮一个LED,那么正常写程序没问题。 如果我们想让LED1和LED6亮,其他灯不亮,则需要开启行1、行2、列1、列2,随之带来的问题就是LED2和LED5也会跟着亮起来。 解决方法类似于扫描,因为单片机运行速度很快,可以在很短的时间内开关数次而肉眼看不到。所以我们可以每次只亮一列(排)灯,亮单位时间后关掉同时开启另外一列(排),如此四次一循环

qq_46615634的博客 5809

数据结构之LinkedList源码分析之插入(add(int Index,E e))核心方法--Day2

hello 世界,偷懒的我来整理LinkList的add方法源码了,(●’◡’●),不清楚Linklist结构的小伙伴可以去看鄙人这篇文章(看完还不懂你打我(●’◡’●)): 《小白入门数据结构(链表)–LinkedList特点分析–超详细方法源码解读-Day1》 首先我们按照返回值来一项项整理Linklist的几种添加(add)的方法: (1)今天分析无返回值的(void): add(int Index,E e) //作用:将给定的值插入到给定的位置index上 源码分析: public void a

唐豌豆的博客 673

python 中心线提取_二值分析 | OpenCV + skimage如何提取中心线

点击上方蓝字关注我们微信公众号:OpenCV学堂关注获取更多计算机视觉与深度学习知识问题前几天有个人问了我一个问题,问题是这样的,他有如下的一张二值图像:怎么得到白色Blob中心线,他希望的效果如下:显然OpenCV中常见的轮廓分析无法获得上面的中心红色线段,本质上这个问题是如何提取二值对象的骨架,提取骨架的方法在OpenCV的扩展模块中,另外skimage包也支持图像的骨架提取。这里就...

weixin_42204453的博客 4292

北斗导航 | 卫星信号捕获跟踪原理解析

卫星信号的捕获与跟踪是导航接收机的"眼睛",其性能直接决定定位精度、动态适应性和抗干扰能力。随着北斗三号全球组网完成,新一代接收机正朝着。两大核心阶段,二者共同构成定位的基础。调制,频谱主瓣宽度达4.092MHz,较传统BPSK调制抗干扰能力提升3dB[38]。的目标持续演进,在自动驾驶、精密农业等领域展现出巨大应用潜力。二维空间中搜索峰值相关能量[4]。卫星导航接收机对信号的处理可分为。北斗三号B1C/B2a信号采用。北斗三号新增的B1C信号采用。

尘世冰封的专栏 787

JAVA容器系列一:LinkedList源码解读

LinkedList是一个实现了List接口和Deque接口的双端链表。 有关索引的操作可能从链表头开始遍历到链表尾部,也可能从尾部遍历到链表头部,这取决于看索引更靠近哪一端。 LinkedList不是线程安全的,如果想使LinkedList变成线程安全的,可以使用如下方式: List list=Collections.synchronizedList(new LinkedList(...)); ...

qq_34748010的博客 501

【异常】安装hermes-agent时提示GnuTLS recv error (-110): The TLS connection was non-properly terminated.

Git克隆仓库时出现TLS连接异常报错的解决方案摘要: 当执行git clone命令时遇到"GnuTLS recv error (-110)"报错,通常由网络不稳定、缓冲区不足或证书验证问题导致。主要解决方案包括:1)增大Git HTTP缓冲区(git config --global http.postBuffer 524288000);2)使用GitHub镜像站加速克隆;3)临时禁用SSL验证进行测试;4)检查并调整代理配置;5)改用SSH协议克隆。建议优先尝试增大缓冲区和镜像站方案,

奶爸的编程之路,也就一周冷个三天 1360

java---ArrayList源码解析

ArrayList 底层就是一个数组,依赖其扩容机制(后面会提到)它能够实现容量的动态增长,所以 ArrayList 就是数据结构中顺序表的一种具体实现。

m0_58196614的博客 1788

Nacos 从困惑到蒙圈(9)Nacos 适配 达梦数据库【最新版】

介绍Nacos适配达梦数据库的详细步骤,包括对最新版本的支持改造。

甘蓝的专栏 1382

工业相机,大恒,面振相机8脚电源线和I/O触发接口线,颜色和接法说明和触发软件设定

上图: 说明一下,工业相机有TTL逻辑电平触发,也有光耦触发等。 这里一般我们用电路板驱动,就用GPIO触发模式, 这里,准备了两个GPIO触发模式,为LINE2,LINE3都可以选择,然后有一个GPIO_GND 如果,你只有一个触发接口,那么如图,选两个就好了。 实际接法如图。 ...

山云的专栏 1万+

源码解析系列:ArrayList(3) - add方法和remove方法

这一部分将会介绍源码中的add方法和remove方法

Jwasx的博客 751

MFC 中实现 WebSocket 客户端以支持实时双向通信

3. **协议兼容**:若服务器使用 `wss://`(加密),需在 `lws_client_connect_info` 中配置 SSL 相关参数(`ssl_connection = LCCSCF_USE_SSL`)。- 编辑框(`m_editUrl`):输入 WebSocket 服务器地址(如 `ws://echo.websocket.events`)。2. 将编译后的库文件(`.lib`、`.dll`)和头文件路径添加到 MFC 项目中(项目属性 -> VC++ 目录)。// UI:服务器地址。

寒寒豆豆软件公司的博客 209

深入剖析LinkedList:揭秘底层原理

本文深入剖析了LinkedList的底层原理,并揭秘了其内部实现机制。LinkedList是一种常见的数据结构,用于存储和操作大量的数据。在文章中,我们首先介绍了LinkedList的基本概念和特点,然后详细解析了它的底层原理。LinkedList采用链表的形式存储数据,每个节点都包含一个值和一个指向下一个节点的引用。这种结构使得在插入和删除元素时具有较低的时间复杂度。接下来,我们分析了LinkedList的插入、删除和访问操作的实现过程,并比较了与其他数据结构(如ArrayList)的性能差异。

忆~遂愿的博客 5918

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

Java 数据结构与算法 ArrayList扩容机制分析与LinkedList源码分析

简单分析了ArrayList的扩容机制和LinkedList部分源码

Naion的博客 502

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

数据结构与算法学习(二)链式存储结构LinkedList源码分析

待编辑

qq_21158307的博客 322

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

黑马Java面试笔记之 集合篇(算法复杂度+ArrayList+LinkedList)

分析ArrayList源码主要从三个方面去翻阅:成员变量,构造函数,关键方法面试官:面试题-ArrayList和LinkedList的区别是什么?候选人底层数据结构ArrayList 是动态数组的数据结构实现LinkedList 是双向链表的数据结构实现操作数据效率ArrayList按照下标查询的时间复杂度O(1)【内存是连续的,根据寻址公式】, LinkedList不支持下标查询查找(未知索引): ArrayList需要遍历,链表也需要遍历,时间复杂度都是O(n)新增和删除。

2201_75550069的博客 994

【Java底层原理】-> Vector & ArrayList & LinkedList 详细分析

Vector & ArrayList & LinkedList 详细分析Ⅰ从面试出发Ⅱ 相关数据结构与算法Ⅲ Java 集合框架设计结构Ⅳ 源码分析① ArrayList② LinkedListⅤ 总结 Ⅰ从面试出发 这篇文章我们先从一个面试问题出发,然后逐步详细分析这三个集合类的原理。 Q: 请你谈一谈,Vector, ArrayList, LinkedList 有什么区别? 下面的答案源引自极客时间,杨晓峰《Java核心技术面试精讲》。 A: 这三者都是实现集合框架中的 List,也就

欢迎来到新世界 535

Java集合类源码分析汇总

Java集合类基础:http://www.cnblogs.com/hzmark/archive/2012/12/17/CollectionBase.html ArrayList源码分析:http://www.cnblogs.com/hzmark/archive/2012/12/20/ArrayList.html ArrayList的removeRange方法分析:http://www.

novelly的专栏 690

【合集】Java进阶——Java深入学习的笔记汇总 &amp; 再论面向对象、数据结构和算法、JVM底层、多线程

spring作为主流的 Java Web 开发的开源框架,是Java 世界最为成功的框架,持续不断深入认识spring框架是Java程序员不变的追求;而spring的底层其实就是Java,因此,深入学习Spring和深入学习Java是硬币的正反面,两者相辅相成,相互促进。本篇博客是一篇不定期持续更新的博客,是一些Java深入学习的笔记汇总。Java进阶(4)——结合类加载JVM的过程理解创建对象的几种方式:new,反射Class,克隆clone(拷贝),序列化反序列化。

begei的博客 1228

java的数据结构与算法的day08

1.和ArrayList类中的情形一样,LinkedList也是有几个思想要注意 它是作为双链表,注意注意它是一个双链,双链表是为了保持每隔操作花费的时间代价 Node类,在LinkedList类中,作为了一个很重要的存在,没有它就实现不了双链。这个类用于创建节点,用来记录节点的位置,一个节点包含数据、前一个结点的链和后一个节点的链。 LinkedListIterator类,抽象了位置的概念,提供了一个私有类,并实现Iterator类。 ...

dfndsf的博客 132

【合集】Java进阶——Java深入学习的笔记汇总 & 再论面向对象、数据结构和算法、JVM底层、多线程、类加载、

spring作为主流的 Java Web 开发的开源框架,是Java 世界最为成功的框架,持续不断深入认识spring框架是Java程序员不变的追求;而spring的底层其实就是Java,因此,深入学习Spring和深入学习Java是硬币的正反面,两者相辅相成,相互促进。本篇博客是一篇不定期持续更新的博客,是一些Java深入学习的笔记汇总。Java进阶(4)——结合类加载JVM的过程理解创建对象的几种方式:new,反射Class,克隆clone(拷贝),序列化反序列化。

m0_74823683的博客 899

Docker、Mysql、算法、2019年个人公众号原创文章

其它 自研精简版MyBatis框架 一键生成数据库字典 搭建Git+Maven+Jenkins看这篇文章就够了 一起回忆那个J2EE开发的时代 Chrome如何安装Axure RP插件 JDK8ArrayList源码分析 算法&数据结构 图解插入、归并排序算法 图解堆排序算法 图解快速排序算法 手写一个栈数据结构 手写一个队列数据结构 ...

lzy_zhi_yuan的博客 241
上一篇: 算法刻意练习之Map系列
下一篇: 结构型设计模式之代理模式
一枚-狗子
博客等级 码龄14年 1619粉丝 192原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值