privatevoidwriteObject(java.io.ObjectOutputStream s)throws java.io.IOException { s.defaultWriteObject(); s.writeInt(size); for (Node<E> x = first; x != null; x = x.next) s.writeObject(x.item); }
反序列化根据数据重建链表,每个数据新生成一个结点,接在链表尾部
标记原尾指针
尾指针指向新结点
如果原来没结点,那就是头结点,否则原尾指针结点接入新结点
LinkedList.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
privatevoidreadObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); int size = s.readInt(); for (int i = 0; i < size; i++) linkLast((E)s.readObject()); } voidlinkLast(E e){ final Node<E> l = last; final Node<E> newNode = new Node<>(l, e, null); last = newNode; if (l == null) first = newNode; else l.next = newNode; size++; modCount++; }
public E get(int index){ checkElementIndex(index); return node(index).item; } Node<E> node(int index){ if (index < (size >> 1)) { Node<E> x = first; for (int i = 0; i < index; i++) x = x.next; return x; } else { Node<E> x = last; for (int i = size - 1; i > index; i--) x = x.prev; return x; } }
publicintindexOf(Object o){ int index = 0; if (o == null) { for (Node<E> x = first; x != null; x = x.next) { if (x.item == null) return index; index++; } } else { for (Node<E> x = first; x != null; x = x.next) { if (o.equals(x.item)) return index; index++; } } return -1; }
publicbooleanremove(Object o){ if (o == null) { for (Node<E> x = first; x != null; x = x.next) { if (x.item == null) { unlink(x); returntrue; } } } else { for (Node<E> x = first; x != null; x = x.next) { if (o.equals(x.item)) { unlink(x); returntrue; } } } returnfalse; }
E unlink(Node<E> x){ final E element = x.item; final Node<E> next = x.next; final Node<E> prev = x.prev;
if (prev == null) { first = next; } else { prev.next = next; x.prev = null; }
if (next == null) { last = prev; } else { next.prev = prev; x.next = null; }
publicvoidaddLast(E e){ linkLast(e); } voidlinkLast(E e){ //获取现在尾部 final Node<E> l = last; //创建新的尾节点,尾节点的next是null final Node<E> newNode = new Node<>(l, e, null); last = newNode; if (l == null) //原来是空链,那么尾节点也是头部 first = newNode; else //原来非空,直接接上 l.next = newNode; size++; modCount++; }