In order to further understand the idea of using the collection of LinkedList to store data, we specially implemented a custom MyLinkedList. The source code is as follows :(if there are any errors, please also give us more suggestions.)

import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Spliterator; import java.util.function.Consumer; /** * look at the LinkedList source code, */ public class MyLinkedList <E> implements Iterable<E> {transient int size; // Transient Node<E> first; <E> last; Public MyLinkedList() {} public Boolean add(E E) {linkLast(E); return true; } private void linkLast(E E) {Node<E> l = last; Node<E> newNode = new Node<>(l, e, null); last = newNode; if (l == null) { first = newNode; } else { l.next = newNode; } size++; } public boolean add(int index, E e) { if (index == size) { linkLast(e); } else { linkBefore(e, node(index)); } return true; } private void linkBefore(E e, Node<E> node) { Node<E> pred = node.prev; Node<E> newNode = new Node<>(pred, e, node); node.prev = newNode; if (pred == null) { first = newNode; } else { pred.next = newNode; } size++; } public E remove(int index) {Node<E> oldNode = Node (index); E element = oldNode.item; Node<E> pred = oldNode.prev; Node<E> succ = oldNode.next; oldNode.prev = oldNode.next = null; if (pred == null) { first = succ; } else { pred.next = succ; } if (succ == null) { last = pred; } else { succ.prev = pred; } size--; oldNode.item = null; return element; } public void clear() { for (Node<E> x = first; x ! = null; ) { Node<E> next = x.next; x.prev = null; x.item = null; x.next = null; x = next; } first = last = null; size = 0; } public E set(int index, E E) {Node<E> Node = Node (index); E item = node.item; node.item = e; return item; } public E get(int index) {return node(index).item; } private Node<E> node(int index) { if (index < (size >> 1)) { Node<E> next = first; for (int i = 0; i < index; i++) next = next.next; return next; } else { Node<E> prev = last; for (int i = size - 1; i > index; i--) prev = prev.prev; return prev; Public Iterator<E> Iterator (int index) {return new Itr(index); } @Override public Iterator<E> iterator() { return new Itr(0); */ private class implements Iterator<E> {private Node<E> lastReturned; private class implements Iterator<E>; private Node<E> next; private int nextIndex; public Itr(int index) { next = (index == size) ? null : node(index); nextIndex = index; } @Override public boolean hasNext() { return nextIndex < size; } @Override public E next() { if (! hasNext()) throw new NoSuchElementException(); lastReturned = next; next = next.next; nextIndex++; return lastReturned.item; } /** * private static class Node<E> {E item; Node<E> prev; Node<E> next; public Node(Node<E> prev, E item, Node<E> next) { this.item = item; this.prev = prev; this.next = next; }}}Copy the code