Rob L
Rob L

Reputation: 3303

Is this the proper way to delete a linked list in C?

I am learning C and getting used to pointers. I was wondering for a simple linked list structure, is this the proper way to delete a list? I was told you have to take care of everything manually (I'm more of a Java guy, but trying to convert). What suggestions or constructive criticism is there for this? Thanks in advance.

/*   assume a struct with: int data; node *next; 
 *   and a global variable node *root; */
void delete_list() {
    if(root==NULL)return;
    node *temp = root;
    while(root!=NULL) {
        temp=root;
        root=root->next;
        free(temp);
    }
}

Upvotes: 1

Views: 88

Answers (1)

abligh
abligh

Reputation: 25129

Yes, your code is fine. You might want delete_list to take a pointer to the root element as a variable, and you could have written it a little more concisely, e.g.

void
delete_list (node *list)
{
    while (list)
    {
        node *tmp = list->next;
        free (list);
        list = tmp;
    }
}

Upvotes: 2

Related Questions