Good Morning/Evening everyone, I'd like to clarify in my head the following concept about linked list functions (In this case recursive).
Let's take the following program that eliminates the duplicates in a linked list recursively :
ElementoDiLista* deleteDuplicates(ElementoDiLista* head) { if (head == NULL) { return NULL; } if (head->next == NULL) { return head; } if (head->info == head->next->info) { ElementoDiLista *tmp; tmp = head->next; head->next = head->next->next; free(tmp); return deleteDuplicates(head); } else { head->next = deleteDuplicates(head->next); return head; } } With the definition of my struct and list this way :
struct el {int info; struct el *next;}; typedef struct el ElementoDiLista; typedef ElementoDiLista *ListaDiElementi; And then in the main i call the function this way :
Lista1 = deleteDuplicates(Lista1); Where Lista1 is declared as follows : ElementoDiLista Lista1 = NULL
My question was, i was used to declare functions that are void or depends on single types (int,float ecc...) I'd like to clarify two things :
Why the function is declared as
ElementoDiLista* deleteDuplicates(ElementoDiLista* head)because to me it is more intuitive this wayListaDiElementi deleteDuplicates (ListaDiElementi *head)but unfortunately,doesn't work.It is not very clear to me why the function returns head or NULL values, but this is the reason i think why in the main Lista1 takes the value of the function, because the function modifies the list itself, am i right ?
I'm sorry if the questions are not very exciting i'm just trying very hard to understand list in general and are quite difficult, Any help or advise would be appreciated,
Thank you all anyway!
void deleteDuplicates(ElementoDiLista **head)where you modify the head pointer inside the function. You want to return the pointer, not the data.ElementoDiLista *is equivalent toListaDiElementiso you can use either of these declarations.typedef ElementoDiLista *ListaDiElementi;is discouraged (because it is now unclear that it concerns a pointer).