Hello

I have 2 ways to delete a linked list, which one is correct?

If I have this linked list:


list = 1 - 2 - 3- 4

Which function will delete list correctly?
1.

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

}

2.

void destroy(node * & list)
{ 
     delete list;
}

Neither.

Its should look something like this :

~LinkedList(){
    List * temp = head;
     while(temp != null){
               temp = temp->next;
               delete head;
               head = temp;              
     }
}

Thanks for ur reply :)

One problem tho. Wont the code above, not delete the very last element in the linked list? Because of the 1st line within the loop -
temp = temp->next; will cause the while loop to break/stop before we get to delete head??

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

     // delete L;   //do we need to put this 
                     //in to delete the very last element??
}

Also is this(my) method better or worse?

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

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