import java.util.NoSuchElementException; public class LinkedList implements List { private static class Node { private T value; private Node prev; private Node next; private Node(T value, Node prev, Node next) { this.value = value; this.prev = prev; this.next = next; } } private static class LinkedListIterator implements Iterator { private LinkedList myList; private Node current; private LinkedListIterator(LinkedList myList) { this.myList = myList; current = myList.head; } public boolean hasNext() { return (current.next != myList.head); } public T next() { if (!hasNext()) { throw new NoSuchElementException(); } current = current.next; return current.value; } } private Node head; private int size; public LinkedList() { head = new Node(null, null, null); head.prev = head.next = head; size = 0; } public Iterator iterator() { return new LinkedListIterator(this); } public int size() { return size; } public E get(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(Integer.toString(index)); } Node p = head.next; for (int i = 0; i < index; i++) { p = p.next; } return p.value; } public void addFirst(E elem) { if (elem == null) { throw new NullPointerException(); } Node after = head.next; head.next = new Node(elem, head, after); after.prev = head.next; size++; } }