Bastava riadattare la funzione proposta in quel thread verso la fine.
Qui c'è un esempio di utilizzo "brutale", la printf() aggiunta nella funzione di deallocazione serve solo a mostrarne il funzionamento ma ovviamente può essere eliminata.
codice:
#include <stdio.h>
typedef struct _node {
int data;
struct _node *next;
} node;
typedef node * node_ptr;
node_ptr erase(node_ptr head)
{
node_ptr temp;
/* caso base: fine lista */
if (head == NULL) {
return NULL;
}
/* caso generico */
if (head -> next != NULL) {
head -> next = erase(head -> next);
}
temp = head -> next;
printf("Deallocazione del nodo con dato: %d\n", head -> data);
free(head);
return temp;
}
void print_list(node_ptr head)
{
while (head != NULL) {
printf("%d ---> ", head -> data);
head = head -> next;
}
printf("NULL\n");
}
int main(void)
{
node_ptr one, two, three, four, five;
one = (node_ptr) malloc(sizeof(node));
two = (node_ptr) malloc(sizeof(node));
three = (node_ptr) malloc(sizeof(node));
four = (node_ptr) malloc(sizeof(node));
five = (node_ptr) malloc(sizeof(node));
one -> data = 1;
one -> next = two;
two -> data = 2;
two -> next = three;
three -> data = 3;
three -> next = four;
four -> data = 4;
four -> next = five;
five -> data = 5;
five -> next = NULL;
printf("Prima stampa:\n");
print_list(one);
/* cancellazione: la funzione restituisce il puntatore alla nuova testa della lista */
one = erase(one);
printf("Seconda stampa:\n");
print_list(one);
return 0;
}