线性存储结构-LinkedList
LinkedList内部采用链表的形式构建,是一个双向链表。除了继承List外,还继承了Deque接口,可以当做堆栈结构使用。
private static final class Link<ET> {
ET data; //数据
Link<ET> previous, next; //前节点、后节点
Link(ET o, Link<ET> p, Link<ET> n) {
data = o;
previous = p;
next = n;
}
}
新增,这里由于是双向链表,根据位置判断是采用头遍历还是尾遍历开始。然后找出当前location节点的数据进行头尾节点的关系绑定。时间复杂度为o(n/2)
@Override
public void add(int location, E object) {
if (location >= 0 && location <= size) {
Link<E> link = voidLink;
if (location < (size / 2)) {
for (int i = 0; i <= location; i++) {
link = link.next;
}
} else {
for (int i = size; i > location; i--) {
link = link.previous;
}
}
Link<E> previous = link.previous;
Link<E> newLink = new Link<E>(object, previous, link);
previous.next = newLink;
link.previous = newLink;
size++;
modCount++;
} else {
throw new IndexOutOfBoundsException();
}
}
删除与新增一致
@Override
public E remove(int location) {
if (location >= 0 && location < size) {
Link<E> link = voidLink;
if (location < (size / 2)) {
for (int i = 0; i <= location; i++) {
link = link.next;
}
} else {
for (int i = size; i > location; i--) {
link = link.previous;
}
}
Link<E> previous = link.previous;
Link<E> next = link.next;
previous.next = next;
next.previous = previous;
size--;
modCount++;
return link.data;
}
throw new IndexOutOfBoundsException();
}
获取元素
@Override
public E get(int location) {
if (location >= 0 && location < size) {
Link<E> link = voidLink;
if (location < (size / 2)) {
for (int i = 0; i <= location; i++) {
link = link.next;
}
} else {
for (int i = size; i > location; i--) {
link = link.previous;
}
}
return link.data;
}
throw new IndexOutOfBoundsException();
}
总结一下,LinkedList采用的是双向链表的存储结构,虽然对元素的操作需要多一个o(n/2)查询的过程,但是对于顺序存储结构,在删除插入的效率上还是有优势,但是在元素的获取上,则比顺序结构采用下标的形式效率低。同时除了List的实现,LinkedList还实现了堆栈的结构管理。