Deleting the entire linked list

This is another common interview question. The interviewer wants to see how you tackle the problem and maintain pointers to correctly de allocate all the memory reserved by the linked list.

Suppose you start with the head element and traverse the list and delete elements as you move along…but wait a minute! Do you advance the pointer first or delete the pointer first? Suppose you advance the pointer than how would you delete the previous node? And if you delete the node than you can’t advance as your node contains the address of the next element.  So to perform this function we would need to maintain two pointers one which would hold the current node and one which would hold the next node in the linked list. Here is a sample code in C++

Void Delete (Node ** head)
{

Node* temp = *head;
while (temp) {

Node * temp1 = temp->next;
delete temp;
temp = temp1;
}

*head = NULL;

}

Updated courtesy supergokhan

 

Advertisements

2 Comments »

  1. supergokhan said

    Good point my friend. However if you are not returning the linked list (like this void function) it wont work as it will just delete the copies of the linked list.
    You must define the function as

    Void Delete (Node ** head)
    {

    Node* temp = *head;
    while (temp) {

    Node * temp1 = temp->next;
    delete temp;
    temp = temp1;
    }

    *head = NULL;

    }

    Regards.

  2. uzubair said

    Thanks for pointing that out ! missed that in a hurry 🙂 Updated with regards to you..

RSS feed for comments on this post · TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: