Delete A Node In Doubly Linked List

There can be atleast three cases possible while deleting a doubly linked list

  • Deletion of first node i.e., head
  • Deletion of middle node
  • Deletion of last node

Delete A Node In Doubly Linked List Code

void deleteNode(struct node **head, int key)
{
    if(*head == NULL)
        return;
    struct node *temp = *head;
    
    while(temp!=NULL && temp->data!=key){
        temp = temp->next;
    }
    if(temp==NULL){
        printf("Key not found\n");
    }
    else if(temp == *head){
        *head = (*head)->next;
        (*head)->prev = NULL;
        free(temp);
    }
    else if(temp->next == NULL){
        temp->prev->next = NULL;
        free(temp);
    }
    else{
        temp->prev->next = temp->next;
        temp->next->prev = temp->prev;
        free(temp);
    }
}

In the above code we are traversing from first to last node until we get the data and the key.

When we get the node then based on type of node i.e, last, first we will change the attributes.

  • If the node is first then we will make the second node as head and delete the first node.
  • If the node is middle then we will link the first and last node by using middle node.
  • If the node is last then we will delete the node by making the previous node next as NULL.
  • That’s it.
Shares
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment