﻿ C++ exercises and solutions: delete item of doubly linked list

# C++ exercises and solutions: delete item of doubly linked list

## C++ OOP: Doubly Linked List

### Delete item of doubly linked list

Step 4: Delete an element of the doubly linked list

To delete an element of the doubly 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 and the previous link of the pfirst 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 to be deleted. Then exchange the links as you see in the picture below. 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 to point to the item staying before the target item to be deleted. Finally set the temporary pointer to NULL.

//C++ code to  delete an item of the doubly linked list

template <class Type>

int i;

bool deleted=false;

if(pfirst!=NULL){ //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;

pfirst->prev=NULL;

temp=NULL;

deleted=true;

}

}

else if(pos>1 && pos<=countitem()){//delete middle item

temp=pfirst;

for(i=1;i<pos;i=i+1){temp=temp->next;}

if(temp->next==NULL) {plast=temp->prev;plast->next=NULL;}

else{

temp->prev->next=temp->next;

temp->next->prev=temp->prev;

}

temp=NULL;

deleted=true;

}

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

}

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

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

}