LinkedList(jdk1.6)
private transient Entry<E> header = new Entry<E>(null, null, null);
定义一个空的Entry对象作为头结点,Entry是其内部定义的一个内部静态类,结构如下:
private static class Entry<E> {
E element;
Entry<E> next;
Entry<E> previous;
Entry(E element, Entry<E> next, Entry<E> previous) {
this.element = element;
this.next = next;
this.previous = previous;
}
}
构造函数
public LinkedList() {
header.next = header.previous = header;
}
即把首结点尾结点都指向头结点
public E getFirst() {
if (size==0)
throw new NoSuchElementException();
return header.next.element;
}
获取元素首节点,如果链表中没有元素,会报NoSuchElementException错误。
public E getLast() {
if (size==0)
throw new NoSuchElementException();
return header.previous.element;
}
获取元素尾结点,同样的,如果链表中没有元素,会报NoSuchElementException错误。
public E removeFirst() {
return remove(header.next);
}
删除首结点,其内部是通过下面函数实现的
private E remove(Entry<E> e) {
if (e == header)
throw new NoSuchElementException();
E result = e.element;
e.previous