import java.util.NoSuchElementException; public class LinkedList implements List { private static class Node { private T value; private Node next; private Node(T value, Node next) { this.value = value; this.next = next; } } private Node head; private int size; public void addFirst(E elem) { if (elem == null) { throw new NullPointerException(); } head = new Node(elem, head); size++; } public void addLast(E elem) { if (elem == null) { throw new NullPointerException(); } if (head == null) { head = new Node(elem, null); } else { Node p = head; while (p.next != null) { p = p.next; } p.next = new Node(elem, null); } size++; } public void add(E elem, int index) { if (elem == null) { throw new NullPointerException(); } if (index < 0 || index > size) { throw new IndexOutOfBoundsException(Integer.toString(index)); } if (index == 0) { head = new Node(elem, head); } else { Node p = head; for (int i=0; i<(index-1); i++) { p = p.next; } p.next = new Node(elem, p.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.next.next != null) { p = p.next; } saved = p.next.value; p.next = null; } size--; return saved; } public int size() { return size; } public boolean isEmpty() { return head == null; } @Override public String toString() { String str = "["; Node p = head; while (p!=null) { if (p != head) { str += ", "; } str += p.value; p = p.next; } str += "]"; return str; } }