C++ exercises solutions: delete item of circularly linked list


Circularly Linked List

Delete item of circularly linked list

To delete an element of the circularly 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.

C++ 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 target item is equal to the plast. If it is really equal, you need to update the plast pointer to point to the traversing pointer. Finally set the temporary pointer to NULL.

C++ Delete middle item of the list  

//C++ code to  delete an item of the circularly linked list
void Delete(int pos){
  int i,val_pos=1;
  if(pfirst!=NULL){ //make sure the Circularly Linked List is not empty.
      ListElem *temp,*del;

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

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

}

  else if(pos>1 && pos<=countitem(pfirst)){//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->data==plast->data)plast=temp; //delete last item
    del=NULL;

}


  else {val_pos=0;cout<<"Invalid position!\n";}

  if(val_pos!=0 && plast!=NULL) plast->next=pfirst; //let the plast points to the pfirst to make the list circularly linked

}

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

}




Comments

kiri comment

 kiri

کس نننت دادا !!!!


2017-04-11



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.