LinkedList 源码小解

一、成员

private transient Entry<E> header = new Entry<E>(null, null, null);
private transient int size = 0;

底层维护的是一个Entry链表(双向循环链表)

二、LinkedList.Entry类

成员

E element; //data
Entry<E> next; //前指针
Entry<E> previous; //后指针

三、方法

1public LinkedList() {
header.next = header.previous = header;
}

该方法构造了一个新的Entry链表,前后指针都指向自身

2public E getFirst() {
if (size==0)
throw new NoSuchElementException();

return header.next.element;
}

获取链表中第一个元素

3public E getLast() {
if (size==0)
throw new NoSuchElementException();

return header.previous.element;
}

获取链表中最后一个元素

4private E remove(Entry<E> e) {
if (e == header)
throw new NoSuchElementException();

E result = e.element;
e.previous.next = e.next;
e.next.previous = e.previous;
e.next = e.previous = null;
e.element = null;
size--;
modCount++;
return result;
}

移除链表中的某个元素

5private Entry<E> addBefore(E e, Entry<E> entry) {
Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);
newEntry.previous.next = newEntry;
newEntry.next.previous = newEntry;
size++;
modCount++;
return newEntry;
}

插入一个元素 

6public boolean addAll(int index, Collection<? extends E> c) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: "+index+
", Size: "+size);
Object[] a = c.toArray();
int numNew = a.length;
if (numNew==0)
return false;
modCount++;

Entry<E> successor = (index==size ? header : entry(index));
Entry<E> predecessor = successor.previous;
for (int i=0; i<numNew; i++) {
Entry<E> e = new Entry<E>((E)a[i], successor, predecessor);
predecessor.next = e;
predecessor = e;
}
successor.previous = predecessor;

size += numNew;
return true;
}

在链表最后面添加

7private Entry<E> entry(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index: "+index+
", Size: "+size);
Entry<E> e = header;
if (index < (size >> 1)) {
for (int i = 0; i <= index; i++)
e = e.next;
} else {
for (int i = size; i > index; i--)
e = e.previous;
}
return e;
}

获得index对应的Entry对象,如果index>size>>1则使用前指针,如果index<size>>1 则使用后指针遍历到索引处

8public int indexOf(Object o) {
int index = 0;
if (o==null) {
for (Entry e = header.next; e != header; e = e.next) {
if (e.element==null)
return index;
index++;
}
} else {
for (Entry e = header.next; e != header; e = e.next) {
if (o.equals(e.element))
return index;
index++;
}
}
return -1;
}

获取元素对应的索引位置

9public boolean removeLastOccurrence(Object o) {
if (o==null) {
for (Entry<E> e = header.previous; e != header; e = e.previous) {
if (e.element==null) {
remove(e);
return true;
}
}
} else {
for (Entry<E> e = header.previous; e != header; e = e.previous) {
if (o.equals(e.element)) {
remove(e);
return true;
}
}
}
return false;
}

移除最后一次出现的元素

10private class ListItr implements ListIterator<E> 

list中用来遍历的iterator类型

11public Iterator<E> descendingIterator() {
return new DescendingIterator();
}

private class DescendingIterator implements Iterator

用于倒序遍历的iterator

 

posted @ 2017-08-21 15:15  薏米仁儿  阅读(112)  评论(0编辑  收藏  举报