Problems about linked list

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!

[code]
Node *remove_head(Node *&head){
if(head!=nullptr){
Node *temp=head;
head=head->next;
return temp;
}
return nullptr;
}
[code]
Node *remove_head(Node *&head){
if(head!=nullptr){
delete head;
head=head->next; //this is the changed one
return head;
}
return nullptr;
}
Last edited on
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;
} 
Understand. Thanks a lot!
Topic archived. No new replies allowed.