import java.util.NoSuchElementException; public class LinkedList implements List { private static class Node { private T value; private Node previous; private Node next; private Node(T value, Node previous, Node next) { this.value = value; this.previous = previous; this.next = next; } } private Node head, tail; private int size; public void addFirst(E elem) { if (elem == null) { throw new NullPointerException(); } head = new Node(elem, null, head); if (tail == null) { tail = head; } size++; } public void addLast(E elem) { if (elem == null) { throw new NullPointerException(); } if (head == null) { head = tail = new Node(elem, null, null); } else { tail.next = new Node(elem, tail, null); tail = tail.next; } size++; } public void add(E elem, int index) { if (elem == null ) { throw new NullPointerException(); } if (index < 0 || index > size) { throw new IndexOutOfBoundsException(index); } if (index == 0) { head = new Node(elem, null, head); if (tail == null) { tail = head; } else { head.next.previous = head; } } else { Node before, after; before = head; for (int i = 0; i < (index-1); i++) { before = before.next; } after = before.next; before.next = new Node(elem, before, after); if (before == tail) { tail = before.next; } else { after.previous = before.next; } } size++; } public E get(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(Integer.toString(index)); } Node p = head; for (int i=0; i p = head; while (p!=null) { if (p != head) { str += ", "; } str += p.value; p = p.next; } str += "]"; return str; } }