/* @(#)IntListIterator.java   29 October 2005 */

/**
 * An IntListIterator traverses an IntList.
 */
public class IntListIterator
{
    IntList list = null;
    
    IntListNode node = null;
    
    
    /**
     * Constructs an iterator for the given IntList.
     * 
     * Throws NullPointerException if the given IntList
     * is null.
     */
    public IntListIterator(IntList thelist) {
        if (thelist == null)
            throw new NullPointerException
                ("Null list in IntListIterator constructor");
        
        list = thelist;
        node = list.getHead();
    }
    
    
    /**
     * Returns true if there is a data item available in
     * the list at the current location of this iterator.
     */
    public boolean hasData() {
        return node != null;
    }
    
    
    /**
     * Returns the current data item.
     * 
     * Advances the iterator to the next data item if more
     * data is available or to the end of the list.
     * 
     * Throwns RuntimeException if the iterator is already
     * at the end of the list, that is, hasData() is false
     * when this method is called.
     */
    public int getData() {
        if (node == null)
            throw new RuntimeException
                ("Request for data at the end of the list");
        
        int contents = node.getData();
        
        node = node.getNext();
        
        return contents;
    }
    
    
    /**
     * Advances the iterator to the next data item if more
     * data is available or to the end of the list.
     *
     * Does nothing if the iterator is already at the end
     * of the list.
     */
    public void advance() {
        if (node != null)
            node = node.getNext();
    }
}
