/** @author Adriano Luchetta @version 3-Dic-2004 @version 21-Nov-2005 */ import java.util.NoSuchElementException; public class ListaSuCatena implements List { // variabili di istanza private ListNode head, tail; // costruttore public ListaSuCatena() { makeEmpty(); } public void makeEmpty() { head = tail = new ListNode(); } public boolean isEmpty() { return (head == tail); } public int size() { int count = 0; ListNode tmp = head; while (tmp != tail) { count++; tmp = tmp.next; } return count; } public ListIterator getIterator() { return new LinkedListIterator(head); } private class LinkedListIterator implements ListIterator { private ListNode current; // nodo che precede la posizione attuale (non è mai null) private ListNode previous; public LinkedListIterator(ListNode h) { current = h; previous = null; } public boolean hasNext() { previous = null; return current.getNext() != null; } public Object next() throws NoSuchElementException { if (!hasNext()) throw new NoSuchElementException(); previous = current; current = current.getNext(); return current.getElement(); } public void add(Object obj) { ListNode n = new ListNode(obj, current.getNext()); current.setNext(n); previous = null; } public void remove() throws IllegalStateException { if (previous == null) throw new IllegalStateException(); previous.setNext(current.getNext()); current = previous; previous = null; } } private class ListNode { private Object element; private ListNode next; public ListNode(Object e, ListNode n) { element = e; next = n; } public ListNode() { element = null; next = null; } public Object getElement() { return element; } public ListNode getNext() { return next; } public void setElement(Object e) { element = e; } public void setNext(ListNode n) { next = n; } } }