Delete a linked list

Write a function to delete a linked list. The function should take a pointer to the head of the list and should delete all the nodes in the linked list. Signature of the function should be like
void deleteList(Node** head);
This function is accepting Node ** and not Node* because it need to change the head also (set it to NULL after deleting the list). An alternate signature can be 
void deleteList(Node** head);
Where the new head of the list (in this case NULL) will be returned. In C++ you may also receive the head pointer as reference.

Solution:

Let me write both the recursive and non-recursive function to delete the list.

The idea is to delete all the nodes and finally assign NULL to head.

Non-Recursive function:
    void deleteList( Node ** head)
    {
        while(*head != NULL)
        {
            Node * temp = *head;
            *head = (*head)->link;
            delete temp;
        }
    }
Recursive Function:

The recursive function also does the same thing, just that each call will delete the node pointed to by head and leave the responsibility

    void deleteList( Node ** head)
    {
        if(*head != NULL)
        {
            Node * temp = *head;
            *head = (*head)->link;
            deleteList(head);
        }
    }

0 Comments

Leave a comment