Deletion of a node at specific location from a double linked list using c

To delete a node at a specific location in a doubly linked list in C, you can follow these steps:


1. Check if the list is empty. If it is empty, there is nothing to delete.

2. If the node to be deleted is the first node, update the head pointer to point to the next node.

3. If the node to be deleted is the last node, update the tail pointer to point to the previous node.

4. If the node to be deleted is in the middle of the list, traverse the list from the head to the node to be deleted.

5. Set the next pointer of the previous node to point to the next node of the node to be deleted.

6. Set the previous pointer of the next node to point to the previous node of the node to be deleted.

7. Free the memory occupied by the node to be deleted.


Here's the code implementation:

```
// Node structure
struct Node {
    int data;
    struct Node* prev;
    struct Node* next;
};

// Function to delete node at specific location
void deleteNode(struct Node** head_ref, struct Node** tail_ref, int position) {
    // Check if list is empty
    if (*head_ref == NULL) {
        printf("List is empty\n");
        return;
    }

    // If node to be deleted is first node
    if (position == 1) {
        struct Node* temp = *head_ref;
        *head_ref = (*head_ref)->next;
        if (*head_ref != NULL) {
            (*head_ref)->prev = NULL;
        }
        free(temp);
        return;
    }

    // Traverse the list to find the node to be deleted
    struct Node* current = *head_ref;
    int count = 1;
    while (current != NULL && count < position) {
        current = current->next;
        count++;
    }

    // If node to be deleted is last node
    if (current == *tail_ref) {
        *tail_ref = (*tail_ref)->prev;
        (*tail_ref)->next = NULL;
        free(current);
        return;
    }

    // If node to be deleted is in the middle of the list
    current->prev->next = current->next;
    current->next->prev = current->prev;
    free(current);
}
```

You can call the `deleteNode()` function with the head and tail pointers of the doubly linked list and the position of the node to be deleted to delete the node at the specified location.



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext