Deleting a Record from a Linked List
Imagine the following linked list:
First ->
Alice Bob Charlie David
-> -> -> NULL
Imagine that we want to delete "Charlie's" record from the list.
Here is the algorithm:
if the record we want to delete is the first record
make the second record the new first record
delete the memory for the old first record
else
loop until we find Charlie or go off the end of the list (if Charlie isn't on the list)
if we got to NULL (Charlie isn't on the list)
print Charlie not found
else
link previous record to Charlie to the record after Charlie
delete the memory for Charlie's record
Given:
struct person
{
string name;
person * next;
};
The code might look something like:
structptr temp,prev;
temp=first; //assume first points to the start of the list
if (first->name=="Charlie")
{
first=first->next;
delete temp;
}
else
{ //loop until we find Charlie or get to the end
while(temp->name!="Charlie" && temp->next!=NULL)
{
prev=temp; //remember previous record
temp=temp->next; //move to the next record
}
if(temp->name=="Charlie") //if we found Charlie
{
prev->next=temp->next; //link the previous record to the record after Charlie
delete temp; //delete the memory for Charlie's record
}
else
cout<<"Charlie is not on the list.";
}