Search code examples
crecursionlinked-listsingly-linked-listfunction-definition

Delete a node with multiple fields in a single Linked List recursively in C


I'm trying to delete all nodes of users having an age that is less than the given limit. Problem is this function's implementation is incorrect. The algorithm must be recursive.

Input Example:

Jennifer 11
John 19
Sarah 17
Mark 24

Output example:

(null) 11
John 19
 17
Mark 24

Here is the code:

struct list *delete_node(struct list *l, int limit) {
    if (l != NULL) {
        if (l->age < limit) {
            struct list *tmp;
            tmp = l->next;
            free(l);
        }
        if (l->next != NULL)
            l->next = delete_node(l->next, limit);
        else
            return l;
    }
}

Solution

  • Seems like the code is missing one line, noted in comment:

        if (l->age < limit){
            struct list* tmp;
            tmp = l->next;
            free(l);
            l = tmp;                   // fix
        }
    

    As answered by "chqrlie for yellow blockquotes", there other problems, which he has fixed in his answer. You commented that it was solved, but I don't know if your fixed code handles all cases (first node, last node, adjacent nodes, ...). You could update your question with the complete solved code.