Home > Net >  Not understanding how a list works in a recursive function in C
Not understanding how a list works in a recursive function in C

Time:10-31

I have trouble understanding what happens to a list when I use a function to insert some values in it. The exercise is to duplicate all the even element of a list. As you can see I wrote some comments (in the function) to better understand what's the problem of my code. The function works without return and I can't understand why. To make it work I have to use it like a void function on the second call. The integral code can be found at https://replit.com/@Vash221/evenDub?v=1

Here you can see just the main function.

/*
Complete the listDupEven function which, given a list, duplicates all even numbers;
The function must use recursion
*/
#include <stdio.h>
#include "TList.h"
//RECURSIVE FUNCTION
TList listDupEven(TList list)
{
  if(list==NULL)
    return list;
  if(list->info%2==0)    
    {
      list=listInsert(list, list->info);
      list=list->link;
    }
  //If I delete the return and use the function like a void it works:
  //listDupEven(list->link);
  return listDupEven(list->link);
  //If I put a return it doesn't work
}
int main(void) {

  TList list=listCreate();
  list=listInsert(list, 1);
  listInsert(list, 2);
  listInsert(list, 3);
  listInsert(list, 4);
  listInsert(list, 5);
  listInsert(list, 6);

  list=listDupEven(list);
  printf("The new list is:\n");
  listPrint(list);
  return 0;
}

CodePudding user response:

the culprit here is this :

if(list==NULL)
    return list;

You are returning a NULL pointer . You can fix this in many ways , for example you can do this :

TList listDupEven(TList list , TList orig)
{                             
  if(list==NULL)              
    return orig;
  if(list->info%2==0)     
    {
      list=listInsert(list, list->info);
      list=list->link;
    }

  return listDupEven(list->link , orig);
 
}

orig is just the original pointer you pass to your function : list = listDupEven(list , list) ;

The reason it did work when removing the return statement (and by that , I imagine you are talking about a void function , rather than a function without return statement , which is undefined behavior by the way) , is because you didn't overwrite your list pointer by NULL .

Edit : This can work also :

TList listDupEven(TList list)
{
  if(list==NULL)
    return NULL;                                                                                               
  if(list->info%2==0)    
    {
      list=listInsert(list, list->info);
      list=list->link;
    }
  listDupEven(list->link); 
  return list;                                                                                                                       
}
  • Related