In: Computer Science
Write a remove(E val) method for DoublyLinkedList class
This method remove the first occurrence of the node that contains
the val.
.
Method to remove the first occurrence of node that contain val in doubly linked list is provided below.
void remove(E val) {
// If head node is null then the list is empty
if(headNode==NULL) {
printf("Empty list");
}
// If the list is not empty
// If the head node contain required val
if(headNode->val == val) {
// If there is more than one node
if(headNode->next != NULL) {
// Update the previous link of next
node of head node
headNode->next->previous=NULL;
// Now update the head node
headNode=headNode->next;
}
// If there is only one node
else
{
// Make head node null
headNode = NULL;
}
}
// If the head node does not contain required value and there is
only one node
else if(headNode->val != val && headNode->next ==
NULL) {
printf("Data not found");
}
// Otherwise make the head node as curr node
curr = headNode;
// Parse through the list until head node or required
node found
while(curr->next != NULL && curr->val != val) {
// Prev node denote the previous node of curr
node
prev = curr;
curr = curr->next;
}
// Check the curr node has required value
if(curr->val == val) {
// Update the prev node next
prev->next = prev->next->next;
// If the next of prev node is not null
if(prev->next!=NULL)
{
// Update the previous link of prev
node
prev->next->previous=prev;
}
// Otherwise make prev as last node
else
{
last=prev;
}
// free the curr node
free(curr);
}
// Otherwise val not found
else
printf("Data not found");
}