# Insert New node at the beginning of the Doubly Linked List

## Insert New node at the beginning of the Doubly Linked List

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:

``````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;
new->prev=NULL;
new->next=NULL;
}
else{
new->prev=NULL;
}

}``````

In this program, we are doing following things:

1. Creating a structure for node, which contains a value and two pointer.
2. After this we are checking if the head is empty so make the new node head.
3. 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.
4. After this make the new node as head.
5. This is how we insert at the beginning.

So this is how the function is working.

``````#include<stdio.h>
#include<stdlib.h>

struct node{
int data;
struct node *next;
struct node *prev;

};

struct node *head = NULL;

void insertAtBeginning(int a){

struct node *new = malloc(sizeof(struct node));
new->data = a;

new->next = NULL;
new->prev = NULL;
}

else{
new->prev = NULL;

}

}

void print()
{
struct node *p = head;
while(p!= NULL)
{
printf("%d ", p->data);
p = p->next;
}
}

int main()
{

insertAtBeginning(10);
insertAtBeginning(20);
insertAtBeginning(30);
print();

return 0;
}``````