LinkedList 的实现原理

前端之家收集整理的这篇文章主要介绍了LinkedList 的实现原理前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

本文为博客园作者所写: 一寸HUI,个人博客地址:https://www.cnblogs.com/zsql/

简单的一个类就直接说了。LinkedList 的底层结构是一个带头/尾指针的双向链表,可以快速的对头/尾节点 进行操作,它允许插 入所有元素,包括 null。 相比数组(这里可以对比ArrayList源码分析进行查看),链表的特点就是在指定位置插入和删除元素的效率较高,但是查找的 效率就不如数组那么高了。如果熟悉双向链表这个数据结构,其实就很简单了,无非就是实现一些数据的添加删除查询,遍历等功能,双向链表的结构图如下:

 

 

每一个数据(节点)都包含3个部分,一个是数据本身item,一个是指向下一个节点的next指针,还有就是指向上一个节点的prev指针,另外,双向链表还有一个 first 指针,指向头节点,和 last 指针,指向尾节点。,在LinkedList类中通过私有的静态内部类Node作为每一个数据的封装。具体实现如下:

  1. private static class Node<E> { //这个类就是用来封装双向链表中的每一个数据,也是上图中的每一个框
  2. E item;
  3. Node<E> next;
  4. Node<E> prev;
  5. Node(Node<E> prev,E element,Node<E> next) {
  6. this.item = element;
  7. this.next = next;
  8. this.prev = prev;
  9. }
  10. }

接下看看LinkList类的定义:

  1. public class LinkedList<E>
  2. extends AbstractSequentialList<E> //继承的类
  3. implements List<E>,Deque<E>,Cloneable,java.io.Serializable //实现的各种接口
  4. {}

 

 

 接下来看看LinkedList这个类的一些属性:就三个属性,一个用来记录双向链表的大小,一个是first节点用来指向链表的头,last用来指向链表的尾

  1. transient int size = 0;
  2. /**
  3. * Pointer to first node.
  4. * Invariant: (first == null && last == null) ||
  5. * (first.prev == null && first.item != null)
  6. */
  7. transient Node<E> first;
  8. * Pointer to last node.
  9. * Invariant: (first == null && last == null) ||
  10. * (last.next == null && last.item != null)
  11. transient Node<E> last;

在看看构造方法

  1. * Constructs an empty list.
  2. public LinkedList() { //空参构造
  3. }
  4. * Constructs a list containing the elements of the specified
  5. * collection,in the order they are returned by the collection's
  6. * iterator.
  7. *
  8. * @param c the collection whose elements are to be placed into this list
  9. * @throws NullPointerException if the specified collection is null
  10. public LinkedList(Collection<? extends E> c) { //通过已有的集合进行构造
  11. this();
  12. addAll(c); //使用addAll()方法把集合中的数据生产LinkedList
  13. }
  14. boolean addAll(Collection<? c) {
  15. return addAll(size,c);
  16. }
  17. boolean addAll(int index,Collection<? c) {
  18. checkPositionIndex(index);
  19. Object[] a = c.toArray(); //把集合转为数组
  20. int numNew = a.length;
  21. if (numNew == 0)
  22. return false;
  23. Node<E> pred,succ;
  24. if (index == size) {
  25. succ = null;
  26. pred = last;
  27. } else {
  28. succ = node(index);
  29. pred = succ.prev;
  30. }
  31. for (Object o : a) { //对数组进行遍历,对每一个元素都封装成Node并添加到LinkedList中
  32. @SuppressWarnings("unchecked") E e = (E) o;
  33. Node<E> newNode = new Node<>(pred,e,);
  34. if (pred == )
  35. first = newNode;
  36. pred.next = newNode;
  37. pred = newNode;
  38. }
  39. if (succ == ) {
  40. last = pred;
  41. } {
  42. pred.next = succ;
  43. succ.prev = pred;
  44. }
  45. size += numNew;
  46. modCount++;
  47. true;
  48. }

接下来看看LinkedList的基本操作,添加删除,遍历,查询

先看添加,从双向链表的结构来看,添加元素可以在链表的头、尾、以及中间的任意位置添加新的元素。因为 LinkedList 有头指针和尾指针,所以在表头或表尾进 行插入元素只需要 O(1) 的时间,而在指定位置插入元素则需要先遍历一下链表, 所以复杂度为 O(n)。首先看看在头部添加元素:

 

 

 看图可以看出,只要把first指向新的node,新的node的next指向原先firt指向的node,再把原先first指向的node的prev指向新的node就可以了。

  1. * Links e as first element.
  2. void linkFirst(E e) {
  3. final Node<E> f = first; //使用临时node
  4. final Node<E> newNode = new Node<>( newNode;
  5. if (f == ) //判断first是否为空
  6. last =
  7. f.prev = newNode; //把f的prev指向新的node
  8. size++; //链表长度加1
  9. modCount++; //记录链表被修改次数
  10. }

在看看在尾部添加,其实和在头部添加一样,只是把first换成了last,逻辑一样

  1. * Links e as last element.
  2. linkLast(E e) {
  3. final Node<E> l = last;
  4. new Node<>(l,1)">);
  5. last =if (l == )
  6. first =
  7. l.next = newNode;
  8. size++;
  9. modCount++;
  10. }

再看看在中间的任意位置添加

 

 

 这个相对来说复杂点点,修改添加前后node的next和prev的指向,修改的相对来说多点点

  1. * Inserts element e before non-null Node succ.
  2. void linkBefore(E e,1)"> succ) { //表示在在succ节点前面添加e元素
  3. // assert succ != null;
  4. final Node<E> pred = succ.prev; //获取succ的前面节点
  5. new Node<>(pred,succ); //把e封装成节点,并把prev指向succ前面节点,把next指向succ节点
  6. succ.prev = newNode; //然后把succ的prev指向新的节点
  7. pred.next = newNode; //把succ的前节点的next只想新的节点
  8. size++; //链表长度+1
  9. modCount++; //修改次数+1
  10. }

添加说完了,就说说删除,其实也很简单

 

 

 删除也是分为从头部、尾部、中间位置删除

先看看从first位置删除

  1. * Unlinks non-null first node f.
  2. private E unlinkFirst(Node<E> f) {
  3. assert f == first && f != null;
  4. final E element = f.item; //获取first中间的元素,用于后面的返回
  5. final Node<E> next = f.next; //获取f的next节点
  6. f.item = ;
  7. f.next = null; help GC 清除
  8. first = next; //把first指向f的next
  9. if (next == )
  10. last =
  11. next.prev = ; //清除
  12. size--; //链表长度-1
  13. modCount++; //修改次数+1
  14. element;
  15. }

看了从头部删除,其实尾部删除也差不多

  1. * Unlinks non-null last node l.
  2. private E unlinkLast(Node<E> l) {
  3. assert l == last && l != null;
  4. l.item;
  5. final Node<E> prev = l.prev;
  6. l.item = ;
  7. l.prev = help GC
  8. last = prev;
  9. if (prev == )
  10. first =
  11. prev.next = ;
  12. size-- element;
  13. }

在看看从指定位置删除

  1. * Unlinks non-null node x.
  2. */
  3. E unlink(Node<E> x) {
  4. assert x != null;
  5. x.item; //获取该节点的值
  6. x.next; //获取该节点的next节点
  7. x.prev; //获取该节点的prev节点
  8. ) { //把该节点的前节点的next指向该节点的next节点,并清除该节点的prev指向
  9. first = next;
  10. } {
  11. prev.next = next;
  12. x.prev = ;
  13. }
  14. ) { //把该节点的next节点的prev指向该节点的prev节点,并清除该节点的next指向
  15. last = prev;
  16. } {
  17. next.prev = prev;
  18. x.next = ;
  19. }
  20. x.item = ; //清除
  21. size-- element;
  22. }

看完增删,那就继续看查相关的方法,也有从头,尾相关的查询方法,都很简单,做判断,然后查询

  1. * Returns the first element in this list.
  2. *
  3. * @return the first element in this list
  4. * NoSuchElementException if this list is empty
  5. E getFirst() {
  6. first;
  7. throw new NoSuchElementException();
  8. f.item;
  9. }
  10. * Returns the last element in this list.
  11. *
  12. * the last element in this list
  13. * E getLast() {
  14. l.item;
  15. }

当然还有指定index查询

  1. * Returns the (non-null) Node at the specified element index.
  2. Node<E> node(int index) {
  3. assert isElementIndex(index);
  1. //判断index是在链表的前半段还是在后半段,如果在前半段就从first向后遍历,否则使用last向前遍历
  1. if (index < (size >> 1)) {
  2. Node<E> x = first;
  3. for (int i = 0; i < index; i++)
  4. x = x.next;
  5. x;
  6. } {
  7. Node<E> x = last;
  8. int i = size - 1; i > index; i-- x.prev;
  9. x;
  10. }
  11. }

其实基本知道了上面的方法基本对双向链表有了一定的熟悉,当然LinkedList还有很多其他的方法,不过很多都是基于上面这些方法的一些封装,例如:

  1. * Inserts the specified element at the beginning of this list.
  2. *
  3. * e the element to add
  4. addFirst(E e) {
  5. linkFirst(e);
  6. }
  7. * Appends the specified element to the end of this list.
  8. *
  9. * <p>This method is equivalent to {@link #add}.
  10. *
  11. * addLast(E e) {
  12. linkLast(e);
  13. }
  14. * Removes and returns the first element from this list.
  15. *
  16. * the first element from this list
  17. * E removeFirst() {
  18. unlinkFirst(f);
  19. }
  20. * Removes and returns the last element from this list.
  21. *
  22. * the last element from this list
  23. * E removeLast() {
  24. unlinkLast(l);
  25. }
  26. #addLast}.
  27. *
  28. * e element to be appended to this list
  29. * {@code true} (as specified by { Collection#add})
  30. boolean add(E e) {
  31. linkLast(e);
  32. ;
  33. }
  34. * Removes the first occurrence of the specified element from this list,* if it is present. If this list does not contain the element,it is
  35. * unchanged. More formally,removes the element with the lowest index
  36. * { i} such that
  37. * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
  38. * (if such an element exists). Returns { true} if this list
  39. * contained the specified element (or equivalently,if this list
  40. * changed as a result of the call).
  41. *
  42. * o element to be removed from this list,if present
  43. * true} if this list contained the specified element
  44. remove(Object o) {
  45. if (o == ) {
  46. for (Node<E> x = first; x != null; x = x.next) {
  47. if (x.item == ) {
  48. unlink(x);
  49. ;
  50. }
  51. }
  52. } {
  53. if (o.equals(x.item)) {
  54. unlink(x);
  55. ;
  56. }
  57. }
  58. }
  59. * Removes all of the elements from this list.
  60. * The list will be empty after this call returns.
  61. clear() {
  62. Clearing all of the links between nodes is "unnecessary",but:
  63. - helps a generational GC if the discarded nodes inhabit
  64. more than one generation
  65. - is sure to free memory even if there is a reachable Iterator
  66. ; ) {
  67. Node<E> next = x.next;
  68. x.item = ;
  69. x.next = ;
  70. x.prev = ;
  71. x = next;
  72. }
  73. first = last = ;
  74. size = 0
  75. * Removes the element at the specified position in this list. Shifts any
  76. * subsequent elements to the left (subtracts one from their indices).
  77. * Returns the element that was removed from the list.
  78. *
  79. * index the index of the element to be removed
  80. * the element prevIoUsly at the specified position
  81. * IndexOutOfBoundsException {@inheritDoc}
  82. public E remove( index) {
  83. checkElementIndex(index);
  84. unlink(node(index));
  85. }
  86. * Returns the index of the first occurrence of the specified element
  87. * in this list,or -1 if this list does not contain the element.
  88. * More formally,returns the lowest index { i} such that
  89. * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,* or -1 if there is no such index.
  90. *
  91. * o element to search for
  92. * the index of the first occurrence of the specified element in
  93. * this list,or -1 if this list does not contain the element
  94. indexOf(Object o) { //查找元素o是否在链表中,并返回index,没找到返回-1
  95. int index = 0)
  96. index;
  97. index++;
  98. }
  99. } (o.equals(x.item))
  100. ;
  101. }
  102. }
  103. return -1;
  104. }

到这里本文就结束了了,如果想知道LinkedList的更多方法,建议去看源码

猜你在找的Java相关文章