My instructor defined the function remove() as:
struct node
{
node *next;
int value;
}
int IntList::remove()
{
node *victim = first;
int result;
if(isEmpty()) throw listIsEmpty();
first = victim->next;
result = victim->value;
delete victim;
return result;
}
Where first “points to the sequence of nodes representing this IntList.”
If victim and first both point to the same thing, and we delete victim, doesn’t this delete first as well?
At the time of deletion, they do not point to the same thing.
Basically what’s happening here is that the the second node is becoming the first node, and then the old first node is being deleted.
Since
first = victim->nextbefore the delete,first == victimwill never be the same unlessvictim->next == victimwhich should never happen in a linked list.For a way simplified example, assume:
Then it goes down like this: