Turning a recursion into an iteration in Java?

℡╲_俬逩灬. 提交于 2020-12-15 00:47:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!