Hello

I am not sure if my function below will completely delete a linked list. I am worried it will delete every element of the list except for the head(first node)?

For example; If I have this linked list below

L -> 1 -> 2 -> 3 -> 4 -> NULL

Will my function delete the 1st node (1)?

void destroy(node * & L)
{

    node *temp = L;
    while(temp != NULL){
        temp = temp->next;
        delete L;
        L = temp;
    }
}
void destroy(node * & L)
{

    node *temp = L;
    while(temp != NULL){
        temp = temp->next;
        delete L;
        L = temp;
    }
}

It seems with the code you have posted you would indeed miss the first node in the list. If you swap the first two lines in the while loop it would delete all the nodes.

Also if you're wanting to delete L you should put L = temp in front of delete.

I have written a new code, I think this should delete all nodes right?

void destroy(node * & L)
{
node *del = L->next;

while (del != NULL) {
L->next = del->next;
delete del;
del = L->next;
}

delete L; // Delete the head of the Linked List

}

Edited 7 Years Ago by gretty: n/a

How come you don't just delete L? Is there a certain reason you're making a copy of the list? I think it would be easier just to delete L.

But yes, it looks like your code deletes all the nodes. :icon_cheesygrin:

Hello

I am not sure if my function below will completely delete a linked list. I am worried it will delete every element of the list except for the head(first node)?

For example; If I have this linked list below


Will my function delete the 1st node (1)?

void destroy(node * & L)
{

    node *temp = L;
    while(temp != NULL){
        temp = temp->next;
        delete L;
        L = temp;
    }
}

I think it will delete all nodes, lets see say node is 1->2->null , has 2 nodes

node *temp = L; //temp now is node1
    while(temp != NULL){ //while temp is != null
        temp = temp->next; //increment temp, temp is now node2
        delete L; //delete node1 
        L = temp; //head is now node2 
    }

Edited 7 Years Ago by firstPerson: n/a

This article has been dead for over six months. Start a new discussion instead.