前景
上次学习了第一个集合ArrayList,今天看看第二个LinkedList
LInkedList
非同步,线程不安全
链接表的优势
链接表的优势正好弥补了数组列表的缺点,ArrayLIst的底层实现是数组(也就是我们常说的顺序表),而LInkedList是我们经常说的链接表,不妨来对比下它们的优劣
- 顺序表:
- 优势:高效的访问
- 劣势:插入删除元素的大动干戈,存储空间固定且连续
- 链接表
- 优势:插入删除元素的高效,存储空间随意
- 劣势:元素访问必须先遍历
源码解析
表和节点,维护的属性
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.
*/
transient Node<E> first;
/**
* Pointer to last node.
*/
transient Node<E> last;
节点类维护的属性,数据,指向前一个的prev和指向后一个next
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;
}
}
可以发现,LInkedList是一个双向链表,并且维护了头尾指针和结点数量
增
add:尾插
public boolean add(E e) {
linkLast(e);
return true;
}
/**
* Links e as last element.
*/
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++;
}
看的出来,尾插法由于尾节点的存在,O(1)时间即可完成
add:指定结点插入
关键方法LInkBefore,node(index)
public void add(int index, E element) {
checkPositionIndex(index);
if (index == size)
linkLast(element);
else
linkBefore(element, node(index));
}
linkBefore方法实现了具体的插入操作,是从头开始遍历的
/**
* Inserts element e before non-null Node succ.
*/
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++;
}
node(index) 返回索引指向的那个结点,实现了结点的遍历(移动)
Node<E> node(int index) {
// assert isElementIndex(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;
}
}
add:头插
public void addFirst(E e) {
linkFirst(e);
}
private void linkFirst(E e) {
final Node<E> f = first;
final Node<E> newNode = new Node<>(null, e, f);
first = newNode;
if (f == null)
last = newNode;
else
f.prev = newNode;
size++;
modCount++;
}
删:remove
LInkedList也提供了各种删除方法,删头,去尾,索引去除,去除指定元素,具体实现都很熟悉了,就不看了
查:
。。。。
为什么打省略号呢- -因为知道有哪些也记不住,主要是弄清楚这里面的结构,别的操作底层我们都熟悉,因为学过数据结构了
精要部分
不难发现,LInkedlIst里面实现了队列和栈的方法,通过查看,队列有专门的阻塞和非阻塞的链表和数组实现,但是栈似乎只有一个继承Vector的数组实现,但是双端队列的阻塞和非阻塞可以帮助实现栈。可能是因为链表也可以实现这些操作,所以涵盖了那部分的内容,之后还要详细的看一下队列和栈是如何实现的,包括同步机制!这个就比较关键的内容