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

Write a contains method for a linked implementation of a sorted list. This metho

ID: 3741764 • Letter: W

Question

Write a contains method for a linked implementation of a sorted list.

This method is written from the implementation perspective, meaning it goes inside of the SortedLinkedList class.

This means you have access to firstNode and numberOfEntries.

This will involve directly accessing the linked structure rather than only invoking existing methods.

You should also take advantage of the knowledge that the list is always sorted.

You can assume T is Comparable.

The method header is:

public boolean contains(T anEntry)

Explanation / Answer

Please find my answer:

Given below is the implementation of contains() method assuming the structure of the list as shown. Here Node class is a nested class, hence there is no need to write Node<T> . If Node is a separate generic class, then it would be written as Node<T>.


public class SortedLinkedList<T extends Comparable<T>> {
class Node
{
T data;
Node next;
}
private Node firstNode;
private int numberOfEntries;
public boolean contains(T anEntry)
{
Node curr = firstNode;

//if no data or we reach an element greater than the one we are looking for, we stop because the list is sorted
while(curr != null && curr.data.compareTo(anEntry) <= 0)
{
if(anEntry.compareTo(curr.data) == 0)
return true;
curr = curr.next;
}
return false;
}
}

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