LinkedList是由一个一个节点连接起来的链表
private static class Node{ E item; Node next; Node prev; Node(Node prev, E element, Node next) { this.item = element; this.next = next; this.prev = prev; } }
增
public boolean add(E e) { linkLast(e); return true; }
public void addFirst(E e) { linkFirst(e); } private void linkFirst(E e) { final Nodef = first; final Node newNode = new Node<>(null, e, f); first = newNode; if (f == null) last = newNode; else f.prev = newNode; size++; modCount++; } public void addLast(E e) { linkLast(e); } void linkLast(E e) { final Node l = last; final Node newNode = new Node<>(l, e, null); last = newNode; if (l == null) first = newNode; else l.next = newNode; size++; modCount++; }
删
public boolean remove(Object o) { if (o == null) { for (Nodex = first; x != null; x = x.next) { if (x.item == null) { unlink(x); return true; } } } else { for (Node x = first; x != null; x = x.next) { if (o.equals(x.item)) { unlink(x); return true; } } } return false; } public E remove(int index) { checkElementIndex(index); return unlink(node(index)); }
改
public E set(int index, E element) { checkElementIndex(index); Nodex = node(index); E oldVal = x.item; x.item = element; return oldVal; }
查
public E get(int index) { checkElementIndex(index); return node(index).item; }
其他
// 检索出第一个元素,但不取出 public E peek() { final Nodef = first; return (f == null) ? null : f.item; } // 检索出第一个元素,同时取出 public E poll() { final Node f = first; return (f == null) ? null : unlinkFirst(f); }