03/12/08 19:07
uranio
Ciao a tutti, sto provando a implementare le funzioni di una lista linkata, però non so come procedere con la funzione di cancellazione di tutta la lista(void destroy(element * h) ), spero che voi possiate aiutarmi grazie in anticipo!!
#include <stdio.h> #include <stdlib.h> struct element { int info; /* valore dell’elemento */ struct element* next; /* indirizzo del prossimo elemento */ }; typedef struct element element; //consente di usare il tipo element come sinonimo del tipo struct element. element* insert(element* list, int n); element* find(element* list, int n); void print_list(element* h); element* delete(element* h, int n); void destroy(element* h); int conta; // variabile globale int main (void){ char c; int n, count=0; element* head; element* prova; head= NULL; prova= NULL; while( ( c = getchar ()) != 'f' ){ /* c e’ il prossimo carattere letto da standard input Il ciclo termina quando c e’ il carattere ’f’ */ switch(c){ case '+': c++; scanf("%d", &n); if( (find(head,n) )== NULL ){ head= insert(head, n); } break; case '?': c++; scanf("%d", &n); prova= find(head, n); if(prova != NULL){ printf("trovato\n"); } else printf("non trovato \n"); break; case '-': c++; scanf("%d", &n); head= delete(head, n); break; case 'c': printf("numero elementi lista: %d\n", conta); break; case 'p': print_list(head); break; case 'd': //printf("%d\n", head->info); destroy(head); break; } } //printf("ciao\n"); return 0; } element* insert(element* list, int n){ element *new_node; new_node= malloc(sizeof(element)); if(new_node == NULL){ exit(EXIT_FAILURE); } new_node -> info = n; new_node -> next = list; conta++; return new_node; } element* find(element* list, int n){ while( list != NULL && list -> info != n){ list= list -> next; } return list; } void print_list(element* h){ int n; element *elemento; elemento= h; while( elemento != NULL ){ n= elemento ->info; printf("n: %d\n", n); elemento= elemento -> next; } } element* delete(element* h, int n){ element *prev, *curr; for(curr= h, prev= NULL; curr !=NULL; prev= curr, curr= curr -> next) if(curr -> info == n) break; if(curr == NULL) //se non ho trovato niente return h; if(prev == NULL) h = h -> next; else prev -> next = curr -> next; free(curr); conta--; return h; } void destroy(element* h){ element *curr,*prev; while( h != NULL ){ h = delete(h, h -> info); h= h -> next; } }
aaa