﻿ C exercises and solutions: delete element

# C exercises and solutions: delete element

## Circularly Linked List

### Delete element of circularly linked list

Step 4: Delete an element of the 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.

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

}