LinkedList为一个双向循环链表,
LinkedList两个属性:
private transient Entry<E> header = new Entry<E>(null, null, null); //链表头,空数据
private transient int size = 0;
public LinkedList() {
header.next = header.previous = header;
}
元素Entry类封装:
Entry为LinkedList的内部静态类。
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;
}
}
内置迭代器ListItr
ListItr <-ListIterator <- Iterator
public interface ListIterator<E> extends Iterator<E> {
boolean hasNext();
E next();
void remove();
boolean hasPrevious();
E previous();
int nextIndex();
int previousIndex();
void set(E e);
void add(E e);
}
获得第i们元素
通过LinkedList的size,折半查找。
private 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; }
Add增加元素
public boolean add(E e) { addBefore(e, header); return true; } private 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; }
Remove删除元素:
public boolean remove(Object o) { if (o==null) { for (Entry<E> e = header.next; e != header; e = e.next) { if (e.element==null) { remove(e); return true; } } } else { for (Entry<E> e = header.next; e != header; e = e.next) { if (o.equals(e.element)) { remove(e); return true; } } } return false; } private 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; }
ArrayList与LinkedList的增删查
增加:在第i位增加一个元素
ArrayList: 需要把第i位及后面的所有元素往后移动一位;且需要扩充元素数组!
LinkedList:循环链表,找到第i位元素,重新指定前驱,后驱;(size/2 折半循环)
删除:删除第i位元素
ArrayList: 需要把第i位后面的所有元素往前移动一位;
LinkedList:循环链表,找到第i位元素,重新指定前驱,后驱;(size/2 折半循环)
查找:获取第i位元素
ArrayList: 数组下标i
LinkedList:循环链表,找到第i位元素(size/2 折半循环)