Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

208
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda