Here is a part of code for deleting an element from the tail a singly Linked List:
int SLList::deleteFromTail()
{
int el = tail->info;
//if the list has only one element
if(head == tail) {
delete head;
head = tail = 0;
}
else {
//some code here...
}
return el
}
Here head
and tail
are pointers to first and last element of LL, respectively.
In the if
block above after delete head
we are setting head = tail = 0
.
But after we have deleted head
, how can we set it's value to something? (NULL
in this case)
Head is a pointer
. You are deleting an object
pointed by the pointer
, not the pointer
itself
Consider this example:
Foo *foo = new Foo(); //foo does not store Foo object. Just an adress of created object.
//do some stuff
delete foo; //object is deleted
foo = new Foo(); //create another Foo and make foo point to it
EDIT
A pointer is just an adress ob an object. When you write delete head
you delete the object pointed by head, but even after deletion head pointer
will point to the same place as before. But dereferencing it (e.g. *head
) will cause problems.