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

refSortedList: public class RefSortedList extends RefList implements SortedListI

ID: 3568312 • Letter: R

Question

refSortedList:

public class RefSortedList extends RefList implements SortedListInterface
{

public RefSortedList()
{
super();
}

public void add(Comparable element)
// Adds element to this list.
{
LLObjectNode prevLoc; // trailing reference
LLObjectNode location; // traveling reference
Comparable listElement; // current list element being compared
boolean moreToSearch;   

// Set up search for insertion point.
location = list;
prevLoc = null;
moreToSearch = (location != null);

// Find insertion point.
while (moreToSearch)
{
listElement = (Comparable)location.getInfo();
if (listElement.compareTo(element) < 0) // list element < add element
{
prevLoc = location;
location = location.getLink();
moreToSearch = (location != null); // stop looking at end of list
}
else
moreToSearch = false; // list element >= add element
}

// Prepare node for insertion.
LLObjectNode newNode = new LLObjectNode(element);

// Insert node into list.
if (prevLoc == null)   
{
// Insert as first node.
newNode.setLink(list);
list = newNode;
}
else
{
// Insert elsewhere.
newNode.setLink(location);
prevLoc.setLink(newNode);
}
numElements++;
}
}

Explanation / Answer


------------------------------------------------------------------------------------------
public void find(Object target){
boolean moreToSearch=true;
  location = list;
while (moreToSearch) {
      listElement = (Comparable)location.getInfo();
      if (listElement.compareTo(target) == 0) { // list element equals target
        System.out.println("Target element found.")
        break;
    } else if(listElement.compareTo(target) > 0){
        System.out.println("Target element is not present.");
moreToSearch = false;
} else {
location = location.getLink();
moreToSearch = (location != null);
}
}
}