Insertion of a node in a double linked list

Inserting a node into a double linked list in C involves creating a new node, linking it with the adjacent nodes, and updating the head or tail pointers if necessary. Here is an example of inserting a node at the beginning and end of a double linked list in C:


```c
void insert_at_beginning(int data) {
    struct node *new_node = (struct node*) malloc(sizeof(struct node));
    new_node->data = data;
    new_node->prev = NULL;
    new_node->next = head;

    if (head != NULL) {
        head->prev = new_node;
    }

    head = new_node;

    if (tail == NULL) {
        tail = new_node;
    }
}

void insert_at_end(int data) {
    struct node *new_node = (struct node*) malloc(sizeof(struct node));
    new_node->data = data;
    new_node->prev = tail;
    new_node->next = NULL;

    if (tail != NULL) {
        tail->next = new_node;
    }

    tail = new_node;

    if (head == NULL) {
        head = new_node;
    }
}
```

In the `insert_at_beginning` function, we create a new node, set its `data` value, and link it with the current head node (if it exists). We update the `prev` pointer of the current head node to point to the new node and set the `head` pointer to the new node. If the list was empty before the insertion, we also set the `tail` pointer to the new node.

In the `insert_at_end` function, we create a new node, set its `data` value, and link it with the current tail node (if it exists). We update the `next` pointer of the current tail node to point to the new node and set the `tail` pointer to the new node. If the list was empty before the insertion, we also set the `head` pointer to the new node.



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