C++ tutorial-delete item of linkedlist


C++ Structure example: building a singly linked list

Step 4: Delete an element of the 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(tr) to point to the element before the element to be deleted and a temporary pointer(temp) 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.

 

//C++ code to  delete an item of the list
void Delete(int pos){
 int i;
 if(countitem()>0){ //make sure the list is not empty.
   ListElem *tr,*temp;

  if(pos==1){//delete the first item
    if(countitem()==1){ //The list contains only one item
       pfirst=NULL;
       plast=NULL;

 }
  else{ //The list contains more than one item
     temp=pfirst;
     pfirst=pfirst->next;
     temp=NULL;
  }

}

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

}


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

}

else printf("%s\n", "No item found\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.