0

Considering a list like 1->2->3->4->5
Tlist is made like this:

typedef struct node{
    int info;
    struct node *link;
}Tnode;

typedef Tnode *Tlist;

I got the function listDeleteOdd which is built like this

Tlist listDeleteOdd(Tlist list) {  

    if (list == NULL) 
        return NULL;

    if (list->info % 2 == 1) {
        Tnode *node = list->link;
        DeleteNode(list);
        return listDeleteOdd(node);
    }
    Tnode *node = listDeleteOdd(list->link);
    list->link = node;
    return list;
};

Delete node just frees the memory of the given node ofc. By the way I dont understand how the value Tnode *node after the second if changes . Like it should be NULL couse the cycle return NULL when the prototype "list" reaches the end. After the cycle reaches the end what happens to node and the end the 'return list;' what it returns ??

I studied recursion some months ago and now it's all so confusing . There is there someone who can explain me how the whole function works properly couse i kinda understand how it works but i think there are some steps which are not really clear in my mind. Thx for the patiente in advance .

1 Answers1

0

The key is defining what listDeleteOdd() does. It returns a pointer to a list of nodes which is either empty or contains only even values — a 'clean list'.

Internally, it does that in three different operations:

  1. The input list is empty (NULL); return NULL (base case).
  2. The first node in the list is odd; capture the next node, delete the current node; recurse to return the clean list starting at the next node.
  3. By elimination, the first node in the list is even. Capture the list of even values starting at the next node (recurse). Make the current node's next pointer (link) point to the clean list, and return the current node as the start of the (now clean) list.
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278