How to remove all nodes from a circular list?

Asked

Viewed 463 times

1

I’m having a hard time getting the logic of how to remove all nodes from a circular list, if someone could give a brief explanation of concept and / or point out the errors in the code I’ve already done would be very 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, already if more than one it does not delete them ... ( Full code here )

  • 1

    You can post the full code so we can reproduce your code?

  • Ghostbin.com/Paste/bmxv4

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 the tail is responsible for marking the last one on the list.

Note that I use a repetition structure in which I keep the node I want to displace on an auxiliary pointer, then I modify the head (head points to the next in what will be out of focus), and finally a delete at the address aux guard to shift the memory.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.