I have a small code snippet for deleting element in linked list. Here is the code:
if (head->data == num) {
delete head;
head = head->next;
}
Can you please explain to me, why this code works. It deletes the head and sets the head to the next element.
When I saw this I thought that this will not work but it works.
It's undefined behavior, so anything can happen, including appearing to work.
When you call delete, you're releasing the memory back to the OS. There's no guarantee that whatever is there is deleted or cleared. So the memory can remain the same as before the delete
, but that's just by chance. Accessing it results in undefined behavior.
A proper approach for this would be:
if (head->data == num) {
aux = head;
head = head->next;
delete aux;
}