I am working with algorithms and got a doubt about deallocating pointers, specifically with removing the first element of a linkedlist, here is the method:
template<typename T>
class LinkedList
{
{
T value;
Node *next;
Node(T value)
{
this->value = value;
this->next = nullptr;
}
Node(T value, Node *next)
{
this->value = value;
this->next = next;
}
~Node()
{
};
};
public:
Node *head;
Node *tail;
LinkedList()
{
this->head = this->tail = nullptr;
}
~LinkedList()
{
Node *curr = this->head;
while (curr != nullptr)
{
Node* next = curr->next;
delete curr;
curr = next;
}
}
void addFirst(T value)
{
Node *newNode = new Node(value);
if (!this->head)
{
this->head = this->tail = newNode;
return;
}
newNode->next = this->head;
this->head = newNode;
}
void removeFirst(){
if(!this->head) return;
Node* tmp = this->head->next;
delete this->head;
this->head = tmp;
}
};
My question is, since tmp points to the next node of head, when deallocating the head, it frees the memory (the value of the head and the reference to the next node). Would that next node become invalid? Could someone explain me further what happens exactly when doing delete this->head?