递归不与方法/返回值的功能才能正常工作。递归只意味着方法/函数自己调用。
你必须保证至少有一个停止条件,但并不要求函数返回一个值。这通常是通过递增地改变每次函数递归调用时通过的一个或多个参数来实现的。当那些/那些参数满足某个条件时,你的函数不再调用它自己,并且所有待处理的操作都被解决了。
我不完全了解你正在尝试做的,但这里的任务是向后将一个字符串递归函数的一个例子。我使用希望不言自明的名称使用PSEUDO函数。
public void writeBackwards(String str) {
// This is the negation of the stop condition, so the stop condition
// is when the string is empty, in which case this function will do
// nothing:
if (!str.isEmpty()) {
char firstCharacter = str.getFirstCharacter();
str = str.removeFirstCharacter();
writeBackwards(str); // the recursive call
// The following operation will be pending, waiting for the
// recursive call to be resolved first:
writeCharacter(firstCharacter);
}
}
使用类级对象来保存递归数据。不好的做法,因为它很难跟踪递归问题/因为你的对象总是在变化,所以实际上很难实现递归。主要用于简单情况下,只和总和/连接一样。 –