자바에서 재귀를 반복으로 바꾸는가?
Nov 29 2020
내가 얻을 스택 오버플로 오류 로 인해 내 재귀 무한 루프를 만드는. 메서드를 반복으로 바꾸면이 작업이 중지되지만 방법을 모르겠습니다!
누구든지 내 재귀를 루프로 바꾸도록 안내 할 수 있습니까?
private int findEmpty(int startPos, int stepNum, String key) {
if (arr[startPos] == null) {
return startPos;
}
return findEmpty(getNextLocation(startPos, ++stepNum, key), stepNum, key);
}
특히 return findEmpty(getNextLocation(startPos, ++stepNum, key), stepNum, key);
오류의 원인입니다!
답변
3 WillNess Nov 29 2020 at 23:09
재귀 호출이 꼬리 위치에 있습니다. 따라서 이미 루프를 설명합니다. 구문 적으로 명시 적으로 지정하면됩니다.
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;
}
}
Java로 코딩하지 않습니다. 위 코드가 어떤 식 으로든 호환되지 않는 경우 의사 코드로 간주하고 적절한 코드로 변경하십시오.
LiveandLetLive Nov 29 2020 at 23:14
전체 arr[startPos]
가 아닌 경우 함수가 반환 되지 않습니다 null
. 다음과 같은 조건을 입력해야합니다.
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);
}