A recursive function in C++ must always have a void return type.
Recursion doesn't work only with methods/functions that return values. Recursion means only that the method/function calls itself.
You must guarantee that there is at least one stop condition but this does not require the function to return a value. This is commonly achieved by incrementally changing one or more arguments that you pass each time the function recursively calls itself. When those arguments satisfy a certain condition your function no longer calls itself and all pending operations are solved.
You can use any mutable Object as a parameter of the recursive function to store the result. For example, the backward-sentence problem you mentioned could be written as:
public void stringReverse(String s, int index, StringBuilder sb) {
if (index < 0)
return;
sb.append(s.charAt(index));
stringReverse(s, index - 1, sb);
}And we called like this
StringBuilder sb = new StringBuilder();
stringReverse(mySentence, mySentence.length() - 1, sb);
Comments
Post a Comment