Source of LinkedListWithIterator.java


  1: import java.util.Iterator;
  2: import java.util.NoSuchElementException;
  3: /**
  4:    A class that implements the ADT list by using a chain of linked nodes.
  5:    The list has an iterator. The class is similar to LList.
  6:    
  7:    @author Frank M. Carrano
  8:    @author Timothy M. Henry
  9:    @version 5.0
 10: */
 11: public class LinkedListWithIterator<T> implements ListWithIteratorInterface<T>
 12: {
 13:    private Node firstNode;
 14:    private int  numberOfEntries;;

 16:    public LinkedListWithIterator()
 17:    {
 18:       initializeDataFields();
 19:    } // end default constructor

 21: /*        < Implementations of the methods of the ADT list go here;
 22:      you can see them in Chapter 12, beginning at Segment 12.7 >
 23:    . . . */
 24:    
 25:    public Iterator<T> iterator()
 26:    {
 27:            return new IteratorForLinkedList();
 28:    } // end iterator

 30:         public Iterator<T> getIterator()
 31:         {
 32:            return iterator();
 33:         } // end getIterator
 34:    
 35:         private class IteratorForLinkedList implements Iterator<T>
 36:         {
 37:       private Node nextNode;

 39:                 private IteratorForLinkedList()
 40:                 {
 41:                         nextNode = firstNode;
 42:                 } // end default constructor
 43:                 
 44:       // Implementations of the methods in the interface Iterator go here.

 46:         } // end IteratorForLinkedList
 47:         
 48:         private class Node
 49:         {
 50:       private T    data; // Entry in list
 51:       private Node next; // Link to next node
 52:       
 53:       private Node(T dataPortion)
 54:       {
 55:          data = dataPortion;
 56:          next = null;
 57:       } // end constructor
 58:       
 59:       private Node(T dataPortion, Node nextNode)
 60:       {
 61:          data = dataPortion;
 62:          next = nextNode;
 63:       } // end constructor
 64:       
 65:       private T getData()
 66:       {
 67:          return data;
 68:       } // end getData
 69:       
 70:       private void setData(T newData)
 71:       {
 72:          data = newData;
 73:       } // end setData
 74:       
 75:       private Node getNextNode()
 76:       {
 77:          return next;
 78:       } // end getNextNode
 79:       
 80:       private void setNextNode(Node nextNode)
 81:       {
 82:          next = nextNode;
 83:       } // end setNextNode
 84:         } // end Node
 85: } // end LinkedListWithIterator