本文摘抄至Yikun的个人博客和chenssy的个人博客
概述
LinkedList以双向链表实现。链表的无容量限制,但双向离岸边本身使用了更多的空间,也需要额外的链表指针操作。
LinkedList实现所有可选的列表操作,并允许所有的元素包括null。由于基于链表使得LinkedList的插入和删除更优于ArrayList,而随机访问则比ArrayList逊色些。
除了实现List接口外,LinkedList类还为在列表的开头及结尾get、remove、和insert元素提供了统一的命名方法。这些操作允许将链接列表用作堆栈、队列或双端队列
此类实Deque接口,为add、poll提供先进先出队列操作,以及其他堆栈和双端队列操作
所有的而操作是按照双重连接列表的需要执行的。在列表中编缩索引的操作将从开头或结尾遍历列表(从靠近指定索引的一端)
同时,与ArrayList一样次实现不是同步的。
如:按下标访问元素——get(i)/set(i,e)需要遍历链表键指针移动到(如果 i>数组大小一半,会从末尾移起)。
插入、删除元素时修改前后节点的指针即可,但还是要遍历部分链表的指针才能移动到下标所指的位置,只有在链表的两头的操作——add()、addFirst()、removeLast()或用iterator()上的remove()能省掉指针的移动。
LinkedList是一个简单的数据结构,与ArrayList不同的是,它是基于链表实现。
Doubly-linked list implementation of the List and Deque interfaces. Implements all optional list operations, and permits all elements (including null).
1 LinkedList<String> list = new LinkedLsit<String>();
2. list.add("语文:1");
3. list.add("数学:2");
4. list.add("英文:3");
结构如下图所示 :
定义
我们先看LinkedList的定义 :
1. public class LinkedList<E> extendds AbstractSequentialList<E>
2. implements List<E>,Deque<E>,Cloneable,java.io.Serializable
从这段代码中我们可以清晰地看出LinkedList继承AbstractSequentialList,实现List、Deque、Cloneable、Serializable。其中AbstractSequentialList提供了 List 接口的骨干实现,从而最大限度地减少了实现受“连续访问”数据存储(如链接列表)支持的此接口所需的工作,从而以减少实现List接口的复杂度。Deque一个线性 collection,支持在两端插入和移除元素,定义了双端队列的操作。
属性
在LinkedList中提供了两个基本属性size、header :
1. private transient Entry<E> header = new Entry<E>(null,null,null);
2. private transient int size = 0 ;
其中size的LinkedList的大小,header表示链表的表头,Entry为节点对象。
1. private static class Entry<E>{
2. E element;//元素节点
3. Entry<E> next;//下一个元素
4. Entry<E> previous;//上一个元素
5.
6. Entry(E element, Entry<E> next, Entry<E> previous) {
7. this.element = element;
8. this.next = next;
9. this.previous = previous;
10. }
11. }
上上面为Entry对象的源代码,Entry为LinkedLsit的内部类,它定义了存储的元素。该元素的前一个元素、后一个元素,这是典型的双向链表定义方式。
构造方法
LinkeList提供了两个构造方法 :LinkedList()和LinkedList(Collection
/**构造一个空列表*/
public LinkedList(){
header.next = header.previous = header;
}
/**构造一个包含指定 collection 中的元素的列表,这些元素按其 collection 的迭代器返回的顺序排列。*/
public LinkedList<Collection<? extends E> c>{
this();
addAll(c);
}
LinkedList()构造一个空列表。里面没有任何元素,仅仅只是将header节点的前一个元素、后一个元素都指向自身。
LinkedList(Collection < ? extends E> c) : 构造一个包含指定 collection 中的元素的列表,这些元素按其 collection 的迭代器返回的顺序排列。该构造函数首先会调用LinkedList(),构造一个空列表,然后调用了addAll()方法将Collection中的所有元素添加到列表中。以下是addAll()的源代码:
1. /**
2. * 添加指定 collection 中的所有元素到此列表的结尾,顺序是指定 collection 的迭代器返回这些元素的顺序。
3. */
4. public boolean addAll(Collection<? extends E> c) {
5. return addAll(size, c);
6. }
7.
8. /**
9. * 将指定 collection 中的所有元素从指定位置开始插入此列表。其中index表示在其中插入指定collection中第一个元素的索引
10. */
11. public boolean addAll(int index, Collection<? extends E> c) {
12 //若插入的位置小于0或者大于链表长度,则抛出IndexOutOfBoundsException异常
13. if (index < 0 || index > size)
14. throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
15. Object[] a = c.toArray();
16. int numNew = a.length; //插入元素的个数
17. //若插入的元素为空,则返回false
18. if (numNew == 0)
19. return false;
20. //modCount:在AbstractList中定义的,表示从结构上修改列表的次数
21 modCount++;
22. //获取插入位置的节点,若插入的位置在size处,则是头节点,否则获取index位置处的节点
23. Entry<E> successor = (index == size ? header : entry(index));
24. //插入位置的前一个节点,在插入过程中需要修改该节点的next引用:指向插入的节点元素
25. Entry<E> predecessor = successor.previous;
26. //执行插入动作
27. for (int i = 0; i < numNew; i++) {
28. //构造一个节点e,这里已经执行了插入节点动作同时修改了相邻节点的指向引用
29. //
30. Entry<E> e = new Entry<E>((E) a[i], successor, predecessor);
31. //将插入位置前一个节点的下一个元素引用指向当前元素
32. predecessor.next = e;
33. //修改插入位置的前一个节点,这样做的目的是将插入位置右移一位,保证后续的元素是插在该元素的后面,确保这些元素的顺序
34. predecessor = e;
35. }
36. successor.previous = predecessor;
37. //修改容量大小
38. size += numNew;
39. return true;
40. }
在addAll()方法中,涉及到了两个方法,一个是entry(int index),该方法为LinkedList的私有方法,主要是用来查找index位置的节点元素。
1. /**
2. 返回指定位置(若存在)的节点元素
3. */
4. private Entry<E> entry(int index){
5. if(index < 0 || index >= size)
6. throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
7. //头部节点
8. Entry<E> e = header ;
9. 判断遍历的方向
10. if(idnex < (size >> 1)){
11. for(int i = 0; i <= index; i++)
12. e = e.next;
13. }else{
14. for(int i = size; i > index; i--)
15. e = e.pervious ;
16. }
17. return e ;
18. }
从该方法有两个遍历方向中我们也可以看出LinkedList是双向链表,这也是在构造方法中为什么需要将header的前、后节点均指向自己。
增加方法
add(E e) : 将指定的元素添加到此列表的结尾。
1. public boolean add(E e){
2. addBefore(e,heaer);
3. return true;
4. }
该方法调用addBefore方法,然后直接返回true,对于addBefore()而言,它为LinkedList的私有方法。
1. private Entry<E> addBefore(E e,Entry<E> entry){
2. //利用Entry构造函数构建一个新节点 newEntry,
3. Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);
4. //修改newEntry的前后节点的引用,确保其链表的引用关系是正确的
5. newEntry.previous.next = newEntry;
6. newEntry.next.previous = newEntry;
7. //容量+1
8. size++;
9 //修改次数+1
10 modCount++;
11 return newEntry;
12. }
addAll(int index,Collection< ? extends E> c) : 将指定colleaction 中的所有元素从指定位置开始插入此列表。
addFirst(E ,e) :将指定元素插入此列表的开头。
addLast(E e) : 将指定的元素添加到此列表的结尾。
移除方法
remove(Object o) : 从此列表中移除首次出现的指定元素(如果存在)。该方法的源代码如下 :
1 public boolean remove(Object o) {
2 if (o==null) {
3 for (Entry<E> e = header.next; e != header; e = e.next) {
4 if (e.element==null) {
5 remove(e);
6 return true;
7 }
8 }
9 } else {
10 for (Entry<E> e = header.next; e != header; e = e.next) {
11 if (o.equals(e.element)) {
12 remove(e);
13 return true;
14 }
15 }
16 }
17 return false;
18 }
该方法首先会判断移除的元素是否为null,然后迭代这个链表找到该元素节点,最后调用remove(Entry<E>),remove(Entry<E> e)为私有方法,是LinkedList中所有移除方法的基础方法,如下 :
1 private E remove(Entry<E> e) {
2 if (e == header)
3 throw new NoSuchElementException();
4
5 //保留被移除的元素:要返回
6 E result = e.element;
7
8 //将该节点的前一节点的next指向该节点后节点
9 e.previous.next = e.next;
10 //将该节点的后一节点的previous指向该节点的前节点
11 //这两步就可以将该节点从链表从除去:在该链表中是无法遍历到该节点的
12 e.next.previous = e.previous;
13 //将该节点归空
14 e.next = e.previous = null;
15 e.element = null;
16 size--;
17 modCount++;
18 return result;
19 }
其他移除方法 :
clear():从此列表中移除所有的元素。
remove():获取并移除此列表的头(第一个元素)。
remove(int index):移除此列表中指定位置的元素。
remove(Object o):从此列表中移除首次出现的指定元素(如果存在)
removeFirst():移除并并返回此列表的第一个元素。
removeFirstOccurrence(Object o):从此列表中移除第一次出现的指定元素(从头部到尾部遍历列表时)。
removeLast():移除并返回此列表的最后一个元素。
removeLastOccurrence(Object o):从此列表中移除最后一次出现的指定元素(从头部到尾部遍历列表时)。
以上为JDK 6.0,以下为8
set和get函数
1 public E set(int index, E element) {
2 checkElementIndex(index);
3 Node<E> x = node(index);
4 E oldVal = x.item;
5 x.item = element;
6 return oldVal;
7 }
8
9 public E get(int index) {
10 checkElementIndex(index);
11 return node(index).item;
12 }
这两个函数都调用了node
函数,该函数会以O(n/2)的性能去获取一个节点,具体实现如下所示:
1 Node<E> node(int index) {
2 // assert isElementIndex(index);
3
4 if (index < (size >> 1)) {
5 Node<E> x = first;
6 for (int i = 0; i < index; i++)
7 x = x.next;
8 return x;
9 } else {
10 Node<E> x = last;
11 for (int i = size - 1; i > index; i--)
12 x = x.prev;
13 return x;
14 }
15 }
就是判断index是在前半区间还是后半区间,如果在前半区间就从head搜索,而在后半区间就从tail搜索。而不是一直从头到尾的搜索。如此设计,将节点访问的复杂度由O(n)变为O(n/2)。
其他的一些查找方法
get(int index):返回此列表中指定位置处的元素。
getFirst():返回此列表的第一个元素。
getLast():返回此列表的最后一个元素。
indexOf(Object o):返回此列表中首次出现的指定元素的索引,如果此列表中不包含该元素,则返回 -1。
lastIndexOf(Object o):返回此列表中最后出现的指定元素的索引,如果此列表中不包含该元素,则返回 -1。