Deleting entire list : C++ Linked List – 4

Question. Given a singly linked list, delete all its nodes.

Solution.

void deleteList ( Node **head)

{

if (! *head)

//if list is empty, there is nothing to delete.

return;

 

Node *curr1 = *head, *curr2 = (*head)->next;

while ( ! curr2)

{

cout << “Deleting node with data: ” << curr1 -> data << endl;

delete curr1;

curr1 = curr2;

curr2 = curr2 -> next;

}

cout << “Deleting node with data: ” << curr1 -> data << endl;

delete curr1; //this is needed to delete the last node.

//all nodes have been deleted.

// set head to null.

*head = 0;

}

—–


2 Responses to Deleting entire list : C++ Linked List – 4

  1. Suresh Saggar says:

    See if your code can handle the following use cases:
    1.
    Node * head = NULL;
    deleteList (&head);

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: