Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider the following Java methods belonging to the LinkedList class. They do n

ID: 3935461 • Letter: C

Question

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

Explanation / Answer

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

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote