I implement the following code to delete element at Head. When program runes to "delete p", it will impact the previous Head and Head gets to NULL. What happened?
Node<T>* p;
p = Head;
Head = Head->next;
delete p;
I implement the following code to delete element at Head. When program runes to "delete p", it will impact the previous Head and Head gets to NULL. What happened?
Node<T>* p;
p = Head;
Head = Head->next;
delete p;
This function will delete the 1st node (node pointed to by head). It returns true if the node was deleted else false if the list is empty.
Using double pointers for the input parameter (head) here because head will have to be updated and this value should reflect outside this function.
bool deleteHeadElement(Node** head)
{
if (*head == nullptr)
{
// List is empty, nothing to delete
return false;
}
// Store the node that has to be deleted
Node* nodeToDelete = *head;
// Update the head to point to next nodeToDelete
*head = nodeToDelete->next;
delete nodeToDelete;
// 1st element of node has been deleted.
return true;
}
After the call to this function, you may subsequently call it and it will take care of the scenario in which the list becomes empty after the previous calls.
NOTE: Regarding the value 0xfeeefeee, it seems you are trying to somehow freeing already freed memory. Perhaps you should check if your head is properly getting updated.
Also, make sure that you are freeing memory of the node by using delete only if it was allocated using new. delete takes care if the memory to pointed is NULL.
If you had allocated memory to the node using malloc(), you should be deallocating using free().