0

Is my approach correct, of trying to get to the end of the linked list and free through it to the top? Does my recursion make sense?

// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
    for (int i = 0; i < HTableSize; i++)
    {
        node *trav = table[i];
        freenode(trav);
        return true;
    }

    return false;
}
//FREE NODE function definition
void freenode(node *trav)
{
    if (trav->next != NULL)
        {
            trav = trav->next;
            freenode(trav->next);
        }
    else
        {
            free(trav);
        }
}

If I try the following code check50 approves my pset, but isn't it freeing in the opposite direction?

bool unload(void)
{
    node* cur, *next;

    // iterate through all buckets/linked-lists of hash_table and free nodes
    for (int i = 0; i < HASH_TABLE_SIZE; i++)
    {
        if (hash_table[i])
        {
            next = hash_table[i];

            do
            {
                cur = next;
                next = cur->next;
                free(cur);
            } 
            while(next);
        }
    }

    return true;
}
0

Your recursion does not make sense. But it's not too far off either.

After calling the function recursively, you would still have to free the current node. But by setting trav = trav->next;, you threw the original away.

You could fix that. First would be to handle the base case. If trav is NULL, there's nothing to do, your function got called with a pointer to an empty linked list. But if trav is not NULL, you would first perform a recursive call for the linked list represented by trav->next (without assigning to trav or another variable first), and then free the current node.

4
  • ok thank you for your help!! – Fermin Bereciartua Mar 27 '20 at 12:49
  • Oh, and of course the for loop should not contain a return. But that's unrelated to the recursion. – Blauelf Mar 27 '20 at 13:04
  • Why not? Shouldn't all functions return? – Fermin Bereciartua Mar 27 '20 at 13:18
  • Not before the work is done, which in this case would be after the loop. Otherwise you would empty only the first bin. – Blauelf Mar 27 '20 at 13:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .