在某种程度上,您应该确保初始化只发生一次。有不同的方法可以做到这一点。
一种方法是在函数之外进行初始化,假设你有这样的东西(伪代码):
function recursiveFunction():
// Here you had your old init code, you don't need it here anymore
// Here your function is the same as before
// [ ... ]
recursiveFunction()
return; // Some return statement
end
// Init stuff here (make sure these variables/list you init are globally defined, so they can be accessed from inside the function
// Then call your recursive function:
recursiveFunction()
另一种简单(但不一定很漂亮)的方法是在初始化完成后将一些全局变量设置为 true,例如:
global variable init_is_done = false // Make sure this can be accessed inside your function
function recursiveFunction():
// Check if init_is_done is true before doing init
if not init_is_done:
// Have your init code here
init_is_done = true
endif
// Here your function is the same as before
// [ ... ]
recursiveFunction()
return; // Some return statement
end
// Now you can just call your function
recursiveFunction()
根据您使用的语言,不同的方法可能会很好。我当然会尝试将 init 东西放在函数之外。希望这对你有用。