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!
getNextLocation, so we can't diagnose the problem without seeing that code. I suspect the following is not your problem, but it also looks like you're using++stepNumin a way you don't expect; the way you have it,stepNumis the same at every iteration and isstepNum+1inside ofgetNextLocation.