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: 3630143 • Letter: P

Question

public class StringNode {

private char ch;

private StringNode next;



/**

* Constructor

*/

public StringNode(char c, StringNode n) {

ch = c;

next = n;

}



public static int lastIndexOf(StringNode str, char ch)
This method should use recursion to find and return the index of the last
occurrence of the character ch in the string str, or -1 if ch does not appear in
str. For example, given the linked-list string str3 created in part d:
• lastIndexOf(str3, 'e') should return 6, because the last occurrence
of 'e' in "recurse" has an index of 6.
• lastIndexOf(str3, 'r') should return 4, because the last occurrence
of 'r' in "recurse" has an index of 4.
• lastIndexOf(str3, 'l') should return -1, because there are no
occurrences of 'l' in "recurse".

Explanation / Answer

public static int lastIndexOf(StringNode str, char ch)
{
      return lastIndexOf_helper(str, ch, 0);
}

// use helper method to keep track of current index of node
private static int lastIndexOf_helper(StringNode str, char ch, int currIndex)
{
      // break case: null string
      if(str == null)
            return -1;
      // look ahead for later index
      int temp = lastIndexOf_helper(str.next, ch, currIndex+1);
      if(temp > 0)
            return temp;
      // check this node
      if(str.ch == ch)
            return currIndex;
}