Consider the following Java methods belonging to the LinkedL

Consider the following Java methods belonging to the LinkedList class. They do not function as described in their comments. What is wrong? How would you fix them?//These methods recursively print the entire list public void printList () {printList(head);} private void printList (Node current) {System. out. print In (current. getDatum ()); if (current.getHextO ! = null) printList (current .getllext());}//These methods return the index of the specified//item in the list (0 = head, 1 = after head, etc.) public int index0f (int target) {return Indexof (target, head); private int index0f (int target, Node current) {if (current

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);
}

 Consider the following Java methods belonging to the LinkedList class. They do not function as described in their comments. What is wrong? How would you fix th

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site