重温数据结构三——LinkedList
来源:互联网 发布:python exit 返回值 编辑:程序博客网 时间:2024/06/01 10:03
我们知道java里面的LinkedList的底层数据结构也是基于链表的,是一个队列来实现的,我们下面就来看看源码的具体实现思路:
public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, java.io.Serializable{ // 链表的长度 transient int size = 0; // 头尾指针,这里是指向头节点或者尾节点 /** * Pointer to first node. * Invariant: (first == null && last == null) || * (first.prev == null && first.item != null) */ transient Node<E> first; /** * Pointer to last node. * Invariant: (first == null && last == null) || * (last.next == null && last.item != null) */ transient Node<E> last; }// 借点内部类,包括指向前驱以及后继的节点,实际上就是双向链表,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; } }//看它的remove方法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; // 处理前驱 // 如果处于第一个位置,那么将头指针first指向它的下一个next // 不在第一个位置,将前面节点的next指向该节点的next if (prev == null) { first = next; } else { prev.next = next; x.prev = null; } //处理后继节点 //如果是最后一个位置,将last指针移到前一个位置 //不在最后一个位置,将后面的节点的前驱指向该节点的前驱 if (next == null) { last = prev; } else { next.prev = prev; x.next = null; } x.item = null; size--; modCount++; return element; }//添加节点到末尾,public boolean add(E e) { linkLast(e); return true; }void linkLast(E e) { //获取链表的最后一个节点 final Node<E> l = last; //构造一个新的节点,指向前驱l final Node<E> newNode = new Node<>(l, e, null); //给尾节点赋值 last = newNode; // 如果链表为空,没有尾节点,那么新的节点是第一个节点,first,last节点都指向它,否则将该节点添加到l节点后面 if (l == null) first = newNode; else l.next = newNode; size++; modCount++; }
看到这里大概就知道LinkedList的实现思路了,就是定义了节点对象,有pre,data,next域,LinkedList定义了first,last来标记头尾元素,增删改查只需要通过first,last指针来定位到具体的位置,然后在然后再进行操作!
0 0
- 重温数据结构三——LinkedList
- 重温数据结构(三)
- 重温数据结构——(1)
- 重温数据结构——(2)
- 重温数据结构——图的遍历
- 重温经典(三)—操作系统
- Java数据结构——LinkedList源码简介
- Java数据结构笔记4——LinkedList
- Java数据结构——ArrayList和LinkedList
- 重温数据结构之链表二——C语言实现
- 重温数据结构之四——队列与堆栈
- 数据结构(Java语言)——LinkedList简单实现
- 【数据结构重温】哈希表
- 【数据结构重温】红黑树
- 重温数据结构二(算法)
- 重温数据结构和算法
- 数据结构--排序之重温
- 重温数据结构-排序算法
- POJ-2485
- java新手——常见的工具问题集合
- Github 的Trending功能,帮你轻松找到有潜力的开源项目
- 正则表达式总结
- jsp之javaBean初理解
- 重温数据结构三——LinkedList
- 获取当前应用程序所在目录
- 概率图模型1:隐马尔科夫(1)
- android studio 编译aidl以及示例demo
- 对双大括号初始化的理解
- 数字二进制位的奇偶位互换
- eclipse在程序修改后,点击运行可以自动保存,如何设置
- css清除浮动
- Android插件化架构设计之加载资源文件