public class LinkedList implements List { private class Node { Object item; Node next; } private Node head; private Node tail; private int size; public LinkedList() { clear(); } public int size() { return size; } public void clear() { size = 0; head = null; tail = head; } public boolean isEmpty() { return size() == 0; } public boolean add(Object x) { Node tmp = new Node(); tmp.item = x; tmp.next = null; if (head == null) head = tmp; else tail.next = tmp; tail = tmp; size++; return true; } private Node find(Object x) { for (Node n = head; n != null; n = n.next) if (n.item.equals(x)) return n; return null; } private Node findPrev(Object x) { for (Node p = head; p.next != null; p = p.next) if (p.next.item.equals(x)) return p; return null; } public boolean remove(Object x) { Node n = find(x); if (n != null) { Node p = findPrev(x); if (n == head) head = n.next; else p.next = n.next; n.next = null; if (n == tail) tail = p; size--; } return n != null; } public boolean contains(Object x) { return find(x) != null; } public Object[] toArray() { Object[] array = new Object[size()]; int i = 0; for (Node n = head; n != null; n = n.next) array[i++] = n.item; return array; } public String toString() { String s = "["; for (Node n = head; n != null; n = n.next) { s += n.item; if (n.next != null) s += ", "; } return s + "]"; } private Node findPosition(int index) { Node n = head; for (int i = 0; i < index; i++) n = n.next; return n; } public Object get(int index) { Node n = findPosition(index); return n.item; } public Object set(int index, Object element) { Node n = findPosition(index); Object item = n.item; n.item = element; return item; } public Iterator iterator() { return new LinkedListIterator(); } private class LinkedListIterator implements Iterator { private Node current; LinkedListIterator() { current = head; } public boolean hasNext() { return current != null; } public Object next() { Object item = current.item; current = current.next; return item; } } }