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

public class StringNode { private char ch; private StringNode next; /** * Constr

ID: 3630145 • Letter: P

Question

public class StringNode {

private char ch;

private StringNode next;



/**

* Constructor

*/

public StringNode(char c, StringNode n) {

ch = c;

next = n;

}

/**

* convert - converts a standard Java String object to a linked-list

* string and returns a reference to the linked-list string

*/

public static StringNode convert(String s) {

if (s.length() == 0)

return null;



StringNode firstNode = new StringNode(s.charAt(0), null);

StringNode prevNode = firstNode;

StringNode nextNode;



for (int i = 1; i < s.length(); i++) {

nextNode = new StringNode(s.charAt(i), null);

prevNode.next = nextNode;

prevNode = nextNode;

}



return firstNode;

}



public static boolean startsWith(StringNode str, StringNode prefix)
This method should use recursion to determine if the string specified by the
parameter str starts with the string specified by the parameter prefix. For
example, let's say that we have used the convert method in the StringNode
class to create several linked-list strings as follows:
StringNode str1 = convert("recursion");
StringNode str2 = convert("recur");
StringNode str3 = convert("recurse");
Given these lines of code, the call startsWith(str1, str2) should return
true, whereas startsWith(str1, str3) should return false. If the second
parameter is null (representing the empty string), the method should
return true, regardless of the value of the first parameter.

Explanation / Answer

public static boolean startsWith(StringNode str, StringNode prefix)
{
// break case: no prefix: return true
if(prefix == null)
return true;
// break case: str is null but prefix is not null: return false
if(str == null)
return false;
// check character in str against character in prefix
if(str.ch != prefix.ch)
return false;
// check next characters
return startsWith(str.next, prefix.next);
}