Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

209
Visualizações
How to turn recursion into iteration?

I get a horrific stackoverflowerror, and figured it was my deep recursion causing it (well, the debugger helped with that...). Can anyone guide me in turning my recursion into a loop?

    H<V>.Pair currPair = (H<V>.Pair) arr[startPos];
    if (arr[startPos] == null) {
        return null;
    }

    if (currPair.key.equals(key)) {
        return currPair.value;
    } else {
        return find(gNL(startPos, ++stepNum, key), key, stepNum);
    }
}

More specifically, return find(getNextLocation(startPos, ++stepNum, key), key, stepNum); causes the recursion.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

This seems to be equivalent:

private V find(int startPos, String key, int stepNum) {

    Hashtable<V>.Pair p;
    boolean finished = false;
    do {
       p = (Hashtable<V>.Pair) arr[startPos]; 
       if (p == null || p.key.equals(key)) {          
           finished = true;
       } else {
           startPos = getNextLocation(startPos, ++stepNum, key);
       }
    } while( ! finished);

    return p == null ? null : p.value;
}
over 4 years ago · Santiago Trujillo Relatório

0

I believe this gets you there:

private V find(int startPos, String key, int stepNum) {
    Hashtable<V>.Pair currPair = arr[startPos];
    while ((currPair != null) && !currPair.key.equals(key)) {
        stepNum++;
        int nextPos = getNextLocation(startPos, stepNum, key);
        currPair = arr[nextPos];
    }

    return (currPair == null)
            ? null
            : currPair.value;
}

The "trick" is to put the conditions you used to end recursion into the loop condition. Note that because your algorithm doesn't use the intermediate results in any way as some other recursive algorithms do, the translation is quite straightforward. This will not work every time with all recursive algorithms, sometimes you'll need to add a data structure to hold your intermediate results.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda