双向链表
注意:
get、set、add、remove、entry、clear
注意entry的循环:
for (Entry e = header.previous; e != header; e = e.previous) {}
新节点的创建:
Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);
此时新加节点已知道其前后节点,但其前节点并不知道后节点发生变化,后节点也不知道前节点发生变化,所以分别将新节点赋给他们。
双向链表节点:
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 class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, java.io.Serializable{ private transient Entry<E> header = new Entry<E>(null, null, null); public LinkedList() { header.next = header.previous = header; } public E get(int index) { return entry(index).element; } public E set(int index, E element) { Entry<E> e = entry(index); E oldVal = e.element; e.element = element; return oldVal; } // 根据给定的索引值离表头近还是离表尾近决定从头还是从尾开始遍历 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; } //默认的添加动作,可以看到这个方法是把新元素添加 到表尾 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; } //默认的删除动作是删除链表的第一个元素,所以说在默认情况下,LinkedList其实扮*演的是一个队列的角色 public E remove() { return removeFirst(); } 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.next = e.next; e.next.previous = e.previous; e.next = e.previous = null; e.element = null; size--; modCount++; return result; } public void clear() { Entry<E> e = header.next; while (e != header) { Entry<E> next = e.next; e.next = e.previous = null; e.element = null; e = next; } header.next = header.previous = header; size = 0; modCount++; } }
相关推荐
earthhouge 2020-08-15
koushr 2020-11-12
范范 2020-10-28
zhaochen00 2020-10-13
Mars的自语 2020-09-27
steeven 2020-09-18
kka 2020-09-14
qiangde 2020-09-13
聚沙成塔积水成渊 2020-08-16
aanndd 2020-08-12
范范 2020-07-30
bluetears 2020-07-28
mingyunxiaohai 2020-07-19
horizonheart 2020-07-19
liushall 2020-07-18
bluetears 2020-07-05
fengshantao 2020-07-02
liuweixiao0 2020-06-27