Write your question here.
Below is a function that remove the first node of a linked list.
Can we change the function to the second one for that purpose?
Why or why not?
Thanks for your help!
The first version doesn't delete anything - though it does return a pointer to the original head. It would be up to the caller to delete the node.
The second tries to dereference a pointer after it has been deleted which is an error.
Maybe this:
1 2 3 4 5 6 7 8 9 10
Node *remove_head(Node *&head)
{
if (head != nullptr)
{
Node *temp = head; // copy the pointer, so it can be deleted later
head = head->next;
delete temp;
}
return head;
}