Is this function wrong? (linked list)

Write your question here.
Below is a function to delete the linked list. I think the last row of it is wrong and should be "current=nullptr", because head has already be deleted.
Is it wrong? Or am I wrong? Why?
Thanks for your help!

1
2
3
4
5
6
7
8
9
10
11
  void delete_list(Node*& head)
{
Node* current = head;
while (current != nullptr)
{
Node* temp = current;
current = current->next;
delete temp;
}
head = nullptr;
}
Your function looks perfect to me.
I've understand the point in line 10.

Thanks!
I think the last row of it is wrong and should be "current=nullptr"
current is a local variable which will dissapear when the function ends, so there would be no point in assigning anything to it just before exiting.

In fact the function might be written without using current at all.
1
2
3
4
5
6
7
8
9
10
11
void delete_list(Node*& head)
{
    
    while (head != nullptr)
    {
        Node* temp = head;
        head = head->next;
        delete temp;
    }

}

Above, there is no need for that last line - when the while loop ends, the value of head is already nullptr, because if it isn't so, the loop would not end but instead execute again...

Topic archived. No new replies allowed.