Insert in a sorted linked list
June 12, 2012
Number series questions
June 12, 2012

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).

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);
        }
    }

1 Comment

  1. vvsnmurthy.vatturi says:

    small correction in recursive function
    void deleteList( Node ** head)
    {
    if(*head != NULL)
    {
    Node * temp = *head;
    *head = (*head)->link;
    deleteList(head);
    free(temp);
    }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *