How to remove all nodes from a circular list?

1

I'm having a hard time picking up the logic of how to remove all nodes from a circular list, if anyone could give a brief explanation of concept and / or point out the errors in the code I've already done, I'd be grateful:

int freelist ( Node ** list ) {

    if ( empty ( list ) ) {

        return 0;

    }

    if ( ( * list ) == ( * list ) -> next ) {

        free ( * list );

        ( * list ) = NULL;

        return 1;

    }

    Node * tmp = NULL, * aux = ( * list ) -> next;

    while ( aux != ( * list ) ) {

        tmp = aux;

        aux = aux -> next;

        free ( tmp );

    }

    // ( * list ) = NULL;

    return 1;

}

If the list contains only one item the function works perfectly, if more than one it does not delete them ... (Full code here )

    
asked by anonymous 25.04.2017 / 17:08

1 answer

1

I built this method in C ++, but it's easy for you to pass it to C.

    void clean() {

    if (head == NULL) {
        cout << "A lista esta vazia\n";
        return;
    }
    else {

        while (head != tail) {
            Node * aux = head;
            head = head->next;
            delete(aux);
        }

        Node * aux = head;
        head = NULL;
        delete(aux);

        cout << "A lista foi esvaziada\n";

    }

}

The head is responsible for marking where the circular list begins, and tail is responsible for marking the last one on the list.

See that I use a repeat structure in which I save the node I want to deallocate on an auxiliary pointer, then I modify the head ( head points to the next in which it will be deallocated), and lastly a delete in the address that helps save the memory.

Notice that I use delete instead of free , because I used the new operator to create a no in my list in C ++. In C, you will use malloc to create the ones in your list, and the free function to deallocate memory.

    
16.05.2018 / 06:58