A doubly linked list is a linear data structure, in which the elements are stored in the form of a node. Each node contains three sub-elements. A data part that stores the value of the element, the previous part that stores the pointer to the previous node, and the next part that stores the pointer to the next node as shown in the below image: The first node also known as HEAD is always used as a reference to traverse the list. The previous of head node and next of last node points to NULL. A doubly linked list can be visualized as a chain of nodes, where every node points to previous and next node. Representation:

In C, a node can be created using structure as shown below:

//node structure
struct Node {
int data;
struct Node* next;
struct Node* prev;
};

Let us create a simple doubly linked list which contains three data nodes.

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

//node structure
struct Node {
int data;
struct Node* next;
struct Node* prev;
};

// test the code
int main() {
//create the head node with name MyList
struct Node* MyList = NULL;

struct Node* first;
//allocate second node in the heap
first = (struct Node*)malloc(sizeof(struct Node));
first->data = 10;
first->next = NULL;
first->prev = NULL;
MyList = first;

struct Node* second;
//allocate second node in the heap
second = (struct Node*)malloc(sizeof(struct Node));
second->data = 20;
second->next = NULL;
second->prev = first;
first->next = second;

struct Node* third;
//allocate third node in the heap
third = (struct Node*)malloc(sizeof(struct Node));
third->data = 30;
third->next = NULL;
third->prev = second;
second->next = third;

return 0;
}

A doubly linked list can be traversed using a temp node. Keep on moving the temp node to the next one and displaying its content. At the end of the list, the temp node will become NULL.

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

//node structure
struct Node {
int data;
struct Node* next;
struct Node* prev;
};

//display the content of the list
printf("The list contains: ");
while (temp != NULL) {
printf("%i ",temp->data);
temp = temp->next;
}
printf("\n");
} else {
printf("The list is empty.\n");
}
}

// test the code
int main() {
//create the head node with name MyList
struct Node* MyList = NULL;

struct Node* first;
//allocate second node in the heap
first = (struct Node*)malloc(sizeof(struct Node));
first->data = 10;
first->next = NULL;
first->prev = NULL;
MyList = first;

struct Node* second;
//allocate second node in the heap
second = (struct Node*)malloc(sizeof(struct Node));
second->data = 20;
second->next = NULL;
second->prev = first;
first->next = second;

struct Node* third;
//allocate third node in the heap
third = (struct Node*)malloc(sizeof(struct Node));
third->data = 30;
third->next = NULL;