将递归转换为Java中的迭代? [英] Turning a recursion into an iteration in Java?

查看:72
本文介绍了将递归转换为Java中的迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我的递归创建了一个无限循环,因此出现了堆栈溢出错误.将方法转换为迭代将停止此操作,但是我不知道如何!

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);
}

具体是return findEmpty(getNextLocation(startPos, ++stepNum, key), stepNum, key);会导致错误!

推荐答案

您的递归调用位于尾部位置.因此,它已经描述了一个循环.只需在语法上使其明确即可:

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;
  }
}

我不使用Java编写代码.如果以上代码在任何方面都不符合要求,请将其视为伪代码,然后更改为合适的代码.

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.

这篇关于将递归转换为Java中的迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆