Consider the following Java methods belonging to the LinkedL
Solution
a. The problem with this code is that, if there are no nodes in the list, it will lead to an exception, as you\'re trying to print the datum first, then checking for next node being null.
So, the solution is:
public void printList()
{
printList(head);
}
private void printList(Node current)
{
if(current != null)
{
System.out.println(current.getDatum());
printList(current.getNext());
}
}
b. The problem with this code is that, it either returns an exception if the element is not found, or will return 0 if the element is found. It will never return any other data value. So, the solution is:
//These methods return the index of the specified item in the list
//(0 = head, 1 = after head, etc.)
public int indexOf(int target)
{
return indexOf(target, head, 0);
}
private int indexOf(int target, Node current, count)
{
if(current == null)
throw new NoSuchElementException();
if(current.getDatum() == target)
return count;
return indexOf (target, current.getNext(), count+1);
}
