Insert at beginning In double linked list

Inserting a node at the beginning of a double linked list in C involves creating a new node, linking it with the current head node, updating the head pointer to point to the new node, and updating the `prev` pointer of the current head node to point to the new node. Here is an example implementation:


```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;
}
```

In this implementation, we create a new node and set its `data` value, `prev` pointer to `NULL`, and `next` pointer to the current head node. We then check if the head node exists. If it does, we update its `prev` pointer to point to the new node. We then set the head pointer to point to the new node.

Note that we first check whether the `head` pointer is `NULL`. If the list is empty, the `head` pointer will be `NULL`, and we simply set it to point to the new node. Otherwise, we need to update the current head node's `prev` pointer to point to the new node.

This implementation assumes that the `node` structure has `prev`, `next`, and `data` fields, and that the `head` pointer points to the first node in the list.



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