问题
I get a stack overflow error due to my recursion creating an infinite loop. Turning the method into an iteration would stop this, but I have no idea how!
Can anyone guide me in turning my recursion into a loop?
private int findEmpty(int startPos, int stepNum, String key) {
if (arr[startPos] == null) {
return startPos;
}
return findEmpty(getNextLocation(startPos, ++stepNum, key), stepNum, key);
}
It is specifically return findEmpty(getNextLocation(startPos, ++stepNum, key), stepNum, key);
that causes the error!
回答1:
Your recursive call is in tail position. Thus it already describes a loop. Just need to make it explicit, syntactically:
private int findEmpty(int startPos, int stepNum, String key) {
while( True )
{
if (arr[startPos] == null) {
return startPos;
}
// return findEmpty(getNextLocation(startPos, ++stepNum, key), stepNum, key);
++stepNum;
int nextPos = getNextLocation(startPos, stepNum, key);
// return findEmpty(nextPos, stepNum, key);
startPos = nextPos;
}
}
I don't code in Java. If the above code is non-compliant in any way, please regard it as a pseudocode and change into something suitable.
回答2:
Your function will never return if arr[startPos]
is not null
throughout. You need to put a condition something like:
private int findEmpty(int startPos, int stepNum, String key) {
if (startPos == arr.length) {
return -1; // The value if no null element is found
}
if (arr[startPos] == null) {
return startPos;
}
return findEmpty(getNextLocation(startPos, ++stepNum, key), stepNum, key);
}
来源:https://stackoverflow.com/questions/65066122/turning-a-recursion-into-an-iteration-in-java