Usuwanie całej listy jednokierunkowej.

Usuwanie całej listy jednokierunkowej.
Blue_Carpet
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 132
0

Witam,
Chcialbym aby na koncu funkcji zawsze byla czyszczona cala lista jednokierunkowa, zrobilem taki cos ale nie trybi:

Kopiuj
struct lista2 *help100 = PoczatekListy2;
    struct lista2 *help101 = PoczatekListy2->next;
    while(help100 != NULL)
    {
        if(help101->next == NULL)
        {
            free(help101);
            help100->next = NULL;
        }
        help100 = help100->next;
        help101 = help101->next;
    }
grzesiek51114
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 2442
4
Kopiuj
void destroy(struct node* root){
    if(root){
        struct node* temp = root;
        struct node* help = root;
        do{
            help = temp;
            temp = temp->next;
            free(help);
        }while(temp);
    }
}
pingwindyktator
  • Rejestracja: dni
  • Ostatnio: dni
  • Lokalizacja: Kraków
  • Postów: 1055
3
Kopiuj
void destroy (struct node *current_node) {
  if (current_node) {
    destroy(current_node->next);
    free(current_node);
  }
}
vpiotr
  • Rejestracja: dni
  • Ostatnio: dni
4

Trochę krótsza wersja by grzesiek51114:

Kopiuj
void destroy(struct node* root){
    struct node* currNode;
    struct node* next = root;

    while(currNode = next) {
       next = currNode->next;
       free(currNode);
    }
        
}
Blue_Carpet
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 132
0

Ale Panowie, mam sobie taką listę, na ktorej mam elementy.

Kopiuj
struct lista2{
    rank y;
    struct lista2 *next;
};
typedef struct lista2 element2;
typedef element2 *ADRES2;
element2 *PoczatekListy2 = NULL;

Chce ją usunąć to jak to zastosować? Tak?:

Kopiuj
if(PoczatekListy2){
        struct lista2 *temp = PoczatekListy2;
        struct lista2 *help = PoczatekListy2;
        do{
            help = temp;
            temp = temp->next;
            free(help);
        }while(temp);
    }
pingwindyktator
  • Rejestracja: dni
  • Ostatnio: dni
  • Lokalizacja: Kraków
  • Postów: 1055
2
Kopiuj
void destroy (element2 *current_node) {
  if (current_node) {
    destroy(current_node->next);
    free(current_node);
  }
}

wywołujesz
destroy(PoczatekListy2);
no litości

Zarejestruj się i dołącz do największej społeczności programistów w Polsce.

Otrzymaj wsparcie, dziel się wiedzą i rozwijaj swoje umiejętności z najlepszymi.