Doubly Linked List in c with proper explanation
Doubly Linked List in c with proper explanation
A doubly linked list is a data structure where each node has three components:
1. A pointer to the previous node.
2. The data itself.
3. A pointer to the next node.
Unlike a singly linked list, where each node points only to the next node, a doubly linked list allows
traversal in both directions — forward and backward.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
Basic Operations
1. Insertion at the Beginning
To insert a new node at the beginning of the list, we update the prev of the current head and next of
the new node to point to the current head.
void insertAtBeginning(struct Node** head, int new_data) {
// Allocate memory for new node
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
// Change the next of the last node to point to the new node
last->next = new_node;
3. Traversal
To traverse the doubly linked list in forward direction:
To traverse the list in backward direction, we first move to the last node, then traverse backward
using the prev pointer:
void traverseBackward(struct Node* node) {
struct Node* last = NULL;
// Traverse backward
while (last != NULL) {
printf("%d -> ", last->data);
last = last->prev;
}
printf("NULL\n");
}
if ((*head) != NULL)
(*head)->prev = new_node;
(*head) = new_node;
}
if (*head == NULL) {
new_node->prev = NULL;
*head = new_node;
return;
}
last->next = new_node;
new_node->prev = last;
}
insertAtEnd(&head, 10);
insertAtEnd(&head, 20);
insertAtBeginning(&head, 5);
insertAtEnd(&head, 30);
return 0;
}