Thursday, 27 September 2018

14.Delete the whole linked list

14.Delete the whole linked list

Logic:
One by one free each node
Starting from head- first take head address into one dummy pointer say cursor then
assign head->next address to cursor  then free head i.e. free memory assigned for head node.

Main function code:
dispose(head);

C function for delete whole linked list :-
void dispose(node *head)
{
    node *cursor, *tmp; // take two dummy pointer
     if(head != NULL)
    {
        cursor = head->next; // take head next pointer into cursor
        head->next = NULL// assign head next as NULL
        free(head);             // Free allocated memory
        head = NULL;          // make head pointer NULL
        while(cursor != NULL)     // for remaining nodes traverse linked list and free cursor
        {
            tmp = cursor->next;
            free(cursor);
            cursor = tmp;
        }
    }
}



No comments:

Post a Comment