LinkedList
来源:互联网 发布:公司封了lol端口 代理 编辑:程序博客网 时间:2024/05/16 05:53
java很多类都源于链表结构设计的,什么是链表结构?我也不知道。。。
LinkedList实现链表的结构主要靠一个内部类Node实现
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; } }
可以看到每个Node都保存了自己和下一个节点和上一个一点,或许这就是链表结构?
不管怎么样先看看LinkedList是如何实现的吧
//增加一个元素public boolean add(E e) { linkLast(e); return true; }//设置last节点为新节点 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++; }//按角标删除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; }//删除的核心方法 E unlink(Node<E> x) { // assert x != null; final E element = x.item; final Node<E> next = x.next; final Node<E> prev = x.prev; //将上一个节点的下一个节点设置为要删除的节点的下一个节点 if (prev == null) { first = next; } else { prev.next = next; x.prev = null; } /将下一个节点的上一个节点设置为要删除的节点的上一个节点 if (next == null) { last = prev; } else { next.prev = prev; x.next = null; } x.item = null; size--; modCount++; return element; }看完LinkedList可以看出性能上是比ArrayList快的,LinkedList不需要考虑数组扩容和copy数组那么LinkedList缺定就在于查询了。如get方法,每次都需要从first 或 last 节点一个一个的找,性能肯定没有数组角标获取的快。public E get(int index) { checkElementIndex(index); return node(index).item; }//查询核心方法 Node<E> node(int index) { // assert isElementIndex(index); //角标大于当前size的一半从first开始检索,否则从last开始 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; } }
0 0
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- python版本--求最长子串
- Android自定义View之LoadingLayout
- Your app must be published under a seller name and company name that reflects the XXXXX brand解决办法
- 《提高SQL查询效率的30种方法》
- Java之路——名词解释(一)
- LinkedList
- Zend Studio12的安装破解注册教程听语音
- Vue- 动态元素属性及v-bind和v-model的区别
- java用命令编译打包可运行jar
- MySQL复制的流程
- Android 矢量图使用
- JAVA安装包制作神器install4j 版本更新至v6.1.5,密码字段选项添加新属性|附下载
- leetcode
- 微信小程序之自定义Toast