遞歸不與方法/返回值的功能才能正常工作。遞歸只意味着方法/函數自己調用。
你必須保證至少有一個停止條件,但並不要求函數返回一個值。這通常是通過遞增地改變每次函數遞歸調用時通過的一個或多個參數來實現的。當那些/那些參數滿足某個條件時,你的函數不再調用它自己,並且所有待處理的操作都被解決了。
我不完全瞭解你正在嘗試做的,但這裏的任務是向後將一個字符串遞歸函數的一個例子。我使用希望不言自明的名稱使用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);
}
}
使用類級對象來保存遞歸數據。不好的做法,因爲它很難跟蹤遞歸問題/因爲你的對象總是在變化,所以實際上很難實現遞歸。主要用於簡單情況下,只和總和/連接一樣。 –