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: 3630142 • 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 void printEveryOther(StringNode str)
This method should use recursion to print every other character in the string
represented by str. For example, let's say that we have used the convert
method in the StringNode class to create a linked list for the string
"method frame" as follows:
StringNode str = convert("method frame");
Given this value of str, the call printEveryOther(str) should print the
following:
mto rm
(Note that the space between the two words is treated like any other
character, and is printed because it is the seventh character in the string.)
The method should print a blank line if null (representing an empty string)
is passed in as the parameter.
Hints: When constructing the parameter for the recursive call, you may need
to take a slightly different approach than the one that we have typically used
when processing linked-list strings recursively. Make sure that your method
works correctly for both even-length and odd-length strings.

Explanation / Answer

public static void printEveryOther(StringNode str)
{
// break case: str == null
if(str == null)
return;
// print this node
System.out.print(str.ch);
// call helper method to skip next node
printEveryOther_helper(str.next);
}
private static void printEveryOther_helper(StringNode str)
{
// break case: str == null
if(str == null)
return;
// otherwise call printEveryOther() with next node to skip this node
printEveryOther(str.next);
}