Design and code a new method to be exported from LinkedStringLog called smallest
ID: 3786635 • Letter: D
Question
Design and code a new method to be exported from LinkedStringLog called smallest, with the following signature:
public String smallest()
The method returns the smallest string in the StringLog. By "smallest", we mean in terms of the lexicographical ordering supported by the String class's compareTo method. As a precondition you should assume that the StringLog is not empty.
Code:
public class LinkedStringLog implements StringLogInterface {
protected LLStringNode log; // reference to first node of linked
// list that holds the StringLog strings
protected String name; // name of this StringLog
public LinkedStringLog(String name) {
// Instantiates and returns a reference to an empty StringLog object
// with name "name".
log = null;
this.name = name;
}
public void insert(String element) {
// Precondition: This StringLog is not full.
//
// Places element into this StringLog.
LLStringNode newNode = new LLStringNode(element);
newNode.setLink(log);
log = newNode;
}
public boolean isFull() {
// Returns true if this StringLog is full, false otherwise.
return false;
}
public int size() {
// Returns the number of Strings in this StringLog.
int count = 0;
LLStringNode node;
node = log;
while (node != null) {
count++;
node = node.getLink();
}
return count;
}
public boolean contains(String element) {
// Returns true if element is in this StringLog,
// otherwise returns false.
// Ignores case difference when doing string comparison.
LLStringNode node;
node = log;
while (node != null) {
if (element.equalsIgnoreCase(node.getInfo())) // if they match
return true;
else
node = node.getLink();
}
return false;
}
public void clear() {
// Makes this StringLog empty.
log = null;
}
public String getName() {
// Returns the name of this StringLog.
return name;
}
public String toString() {
// Returns a nicely formatted string representing this StringLog.
String logString = "Log: " + name + " ";
LLStringNode node;
node = log;
int count = 0;
while (node != null) {
count++;
logString = logString + count + ". " + node.getInfo() + " ";
node = node.getLink();
}
return logString;
}
}
Explanation / Answer
// Here is the required method. Can't test as full code is not provided.
public String smallest()
{
LLStringNode node;
node = log;
String smallest;
if (log != null)
{
smallest = log.name;
}
while (node != null) {
node = node.getLink();
if (node.name.compareTo(smallest) < 0)
{
smallest = node.name;
}
}
return smallest;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.