import java.util.Iterator; public class GenericList implements Iterator, Iterable{ private GenericNode head; private GenericNode iter; int count; public GenericList() { head = null; } public void clear() { head = null; } public void insert(T item) { GenericNode node = new GenericNode(item); insert(node); } public void insert(GenericNode node) { node.next = head; head = node; count ++; } public void insert(GenericNode n, int index) { if (index == 0) insert(n); GenericNode prev, cur; prev = head; cur = head.next; while (cur != null && index > 1) { cur = cur.next; prev = prev.next; index--; } prev.next = n; n.next = cur; count ++; } // Delete the node at the zero-based index. public void remove(int index) { int cur; GenericNode curnode = head; for (cur = index; cur > 1; cur--) curnode = curnode.next; if (curnode == head) head = head.next; else curnode.next = curnode.next.next; count --; } public void remove() { remove(0); } public T getVal(int index) { int cur; GenericNode curnode = head; for (cur = index; cur > 0; cur--) curnode = curnode.next; // curnode should point to the node whose value we want. return curnode.getValue(); } public void print() { head.print(); } public String toString() { String res = ""; GenericNode node = head; while (node.next != null) { res += node.getValue() + ", "; node = node.next; } res += node.getValue() + ">"; return res; } public int length() { return count; } //method required by Iterator public boolean hasNext() { return (iter != null); } //method required by Iterator public T next() { // TODO Auto-generated method stub T data = iter.getValue(); iter = iter.next; return data; } //method required by Iterable public Iterator iterator() { iter = head; return this; } }