Iterators in Simple Linked Lists
We consider the simple linked list from the text where new nodes are inserted in the front of the list. First,
the definition of a Node:
public class Node {
private String name;
private double gpa;
private double amountDue;
private Node next;
public Node(String s, double g, double a)
{
name=s;
gpa=g;
amountDue=a;
next=null;
}
public void setNext(Node x)
{
next=x;
}
public Node getNext()
{
return next;
}
public String toString()
{
return name+" " +gpa+" "+amountDue;
}
}
Next , the declaration of the Linked List with an iterator:
public class LinkedList {
private Node front;
private Node iterator;
public LinkedList()
{
front=null;
}
public void insertFront(String n,double g, double a )
{
Node toInsert=new Node(n,g,a);
toInsert.setNext(front);
front=toInsert;
}
public void initIterator()
{
iterator=front;
}
public boolean hasNext()
{
return (iterator!=null);
}
public Node getNext()
{
Node temp=iterator;
iterator=iterator.getNext();
return(temp);
}
}
And now, we put it all together:
public class UseIt {
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkedList myList=new LinkedList();
Node temp;
myList.insertFront("sam", 3.4, 8000.00);
myList.insertFront("ellen", 3.2, 9000.00);
myList.insertFront("fred", 3.6, 3000.00);
myList.insertFront("mary", 2.8, 7000.00);
myList.insertFront("harry", 3.1, 18000.00);
//Using the iterator
myList.initIterator();
while(myList.hasNext())
{
temp=myList.getNext();
//Now that we have a reference
inside the linked list, we can do whatever we like
System.out.println(temp);
}
}
}