// This class manages a bunch of ListNodes
public class LinkedList
{
private ListNode head; // reference to first node in list
public LinkedList ()
{
head = null;
}
public void addToFront (int val)
{
// Create new ListNode, set it to point to head, and
// then re-route head to point to the new node
ListNode temp = new ListNode(val);
temp.setNext(head);
head = temp;
}
public void print()
{
ListNode traveller = head; // traveller is NOT a node!
while (traveller != null) // While we're still in the list
{
System.out.print(traveller.getData() + " -> ");
traveller = traveller.getNext(); // Move to next node
}
System.out.println("/");
}
public int length () // Iterative (loop-based) version
{
int count = 0;
ListNode trav = head;
while (trav != null)
{
count++;
trav = trav.getNext();
}
return count;
}
private int lengthRec (ListNode foo) // Recursive version of length()
{
if (foo == null) // base case: empty list
return 0;
else // Recursive case: return 1 plus length of subsequent list
return 1 + lengthRec(foo.getNext());
}
public int lengthRec () // "Facade" to hide head of list from user
{
return lengthRec(head);
}
}