Jun 122012
 

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

  One Response to “Delete a linked list”

Comments (1)
  1. 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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)