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

**How To Insert A Node At The End of A Doubly Linked List**

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

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 prev NULL and the next also NULL.
- If the head is not empty then traverse and find the last node which is not NULL and make the new node prev point to last node and the new node next NULL.
- This is how we insert at the end.

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 insertAtEnd(int a){
struct node *new = malloc(sizeof(struct node));
new->data=a;
if(head==NULL){
new->prev=NULL;
new->next=NULL;
head = new;
}
else{
struct node *temp = head;
while(temp->next != NULL){
temp=temp->next;
}
temp->next = new;
new->prev = temp;
new->next = NULL;
}
}
void print()
{
struct node *p = head;
while(p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
}
int main()
{
insertAtEnd(1);
insertAtEnd(2);
insertAtEnd(3);
print();
return 0;
}
```