0

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;
    }
}
3
Contributors
4
Replies
5
Views
8 Years
Discussion Span
Last Post by firstPerson
0
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.

0

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 by gretty: n/a

0

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:

0

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 by firstPerson: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.