delete a head node in link list
To delete a head node in a linked list in C++, follow these steps:
- Create a temporary pointer called
temp
and point it to the head of the linked list. - Move the head pointer to the next node in the linked list.
- Delete the node that
temp
is pointing to. - Set the
temp
pointer tonullptr
to avoid any dangling pointers. - Free the memory occupied by the node pointed to by
temp
.
Here is the code snippet that demonstrates these steps:
void deleteHeadNode(Node*& head) {
if (head == nullptr) {
// Linked list is empty, nothing to delete
return;
}
Node* temp = head;
head = head->next;
delete temp;
temp = nullptr;
}
In this code, Node
is the struct or class representing each node in the linked list, and next
is a pointer to the next node. The head
parameter is passed by reference to update the head pointer in the calling function.
The first step checks if the linked list is empty. If it is, there is nothing to delete, so the function returns.
Next, the temp
pointer is set to the current head node.
Then, the head pointer is moved to the next node by assigning head
to head->next
.
After that, the node pointed to by temp
is deleted using the delete
keyword.
To avoid any potential issues with dangling pointers, the temp
pointer is set to nullptr
.
Finally, the memory occupied by the node pointed to by temp
is freed using the delete
operator.
By following these steps, you can successfully delete the head node in a linked list using C++.