C++ exercises and solutions-delete item of linked list-OOP

Delete item of singly linked list

Step 4: Delete an element of the singly linked list

To delete an element of the linked list, you need to consider the followings:

1. If the element to be deleted is the first element of the list and the list contains only one element, you only need to assign NULL to the pfirst and plast pointers. If the element to be deleted is the first element of the list and the list contain more than one element, you need a temporary pointer to point to the pfirst then move the pfirst to point to its next element and set the temporary pointer to NULL.

Delete the first item of the list  

2. If the element to be deleted is in the middle of the list, you need a traversing pointer(temp) to point to the element before the element to be deleted and a temporary pointer(del) to point to the element to be deleted. Then let the link of the traversing pointer to point to the link of the temporary pointer. To handle situation where the element to be deleted is the last element of the list, you need to test whether the link of the temporary pointer is NULL. If it is really NULL, you need to update the plast pointer to point to the traversing pointer. Finally set the temporary pointer to NULL.

Delete middle item of the list  

//C++ code to delete an item from the linked list
template <class Type>
void LinkedList<Type>::Delete(int pos){

int i;
bool deleted=false;
if(countitem()>0){ //make sure the list is not empty.
ListElem<Type> *temp,*del;

if(pos==1){//delete the first item
if(countitem()==1){ //The list contains only one item
pfirst=NULL;
plast=NULL;
deleted=true;
}
else{ //The list contains more than one item
temp=pfirst;
pfirst=pfirst->next;
temp=NULL;
deleted=true;
}

}

else if(pos>1 && pos<=countitem()){//delete middle item
temp=pfirst;
for(i=1;i<pos-1;i=i+1){temp=temp->next;} //move to the item staying before the target item to be deleted
del=temp->next; //target item to be deleted
temp->next=del->next;
if(del->next==NULL)plast=temp; //delete last item
del=NULL;
deleted=true;
}


else cout<<"Invalid position!\n";

}

else cout<<"No item found\n";

if(deleted!=false)cout<<"Deleted\n";

}




Comments




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.