Hello Coders! Welcome to nkcoderz blog, In this post, you will learn how to insert new node at the beginning of the Doubly Linked List, Code for the above task given below:

**How To Insert Node At The Beginning of the Doubly Linked List**

```
struct node{
struct node *prev;
int data;
struct node *next;
};
struct node *head = NULL;
void insertElementAtBeginning(int val){
struct node *new = malloc(sizeof(struct node));
new->data=val;
if(head==NULL){
new->prev=NULL;
new->next=NULL;
head = new;
}
else{
new->prev=NULL;
new->next=head;
head->prev=new;
head = new;
}
}
```

In this program, we are doing following things:

- Creating a structure for node, which contains a value and two pointer.
- After this we are checking if the head is empty so make the new node head.
- If the head is not empty then make the new node previous pointer null and next pointer points to head and make the head prev node points to next of new node.
- After this make the new node as head.
- This is how we insert at the beginning.

So this is how the function is working.

```
#include<stdio.h>
#include<stdlib.h>
struct node{
struct node *prev;
int data;
struct node *next;
};
struct node *head = NULL;
void insertElementAtBeginning(int val){
struct node *new = malloc(sizeof(struct node));
new->data=val;
if(head==NULL){
new->prev=NULL;
new->next=NULL;
head = new;
}
else{
new->prev=NULL;
new->next=head;
head->prev=new;
head = new;
}
}
void print()
{
struct node *temp = head;
while(temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
}
int main()
{
insertElementAtBeginning(1);
insertElementAtBeginning(2);
insertElementAtBeginning(3);
print();
return 0;
}
```