A doubly linked list in C is a powerful data structure used for efficient insertion and deletion operations at both ends of a list. Unlike a singly linked list, each node in a doubly linked list contains two pointers—one to the next node and one to the previous node. This allows traversal in both directions.
In this article, you will learn how to implement a doubly linked list in C that performs the following operations:
- Insert a node at the front
- Insert a node at the end
- Delete the last node
- Delete a node before a specified position
This guide is ideal for students learning data structures using C programming.
C Program to Implement Doubly Linked List in C
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* prev;
struct Node* next;
};
struct Node* head = NULL;
void insertFront(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->prev = NULL;
newNode->next = head;
if (head != NULL)
head->prev = newNode;
head = newNode;
}
void insertEnd(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
if (head == NULL) {
newNode->prev = NULL;
head = newNode;
return;
}
struct Node* temp = head;
while (temp->next != NULL)
temp = temp->next;
temp->next = newNode;
newNode->prev = temp;
}
void deleteLast() {
if (head == NULL)
return;
struct Node* temp = head;
while (temp->next != NULL)
temp = temp->next;
if (temp->prev != NULL)
temp->prev->next = NULL;
else
head = NULL;
free(temp);
}
void deleteBeforePosition(int pos) {
if (head == NULL || pos <= 1)
return;
struct Node* temp = head;
int i = 1;
while (temp != NULL && i < pos - 1) {
temp = temp->next;
i++;
}
if (temp == NULL)
return;
if (temp->prev != NULL)
temp->prev->next = temp->next;
if (temp->next != NULL)
temp->next->prev = temp->prev;
if (temp == head)
head = temp->next;
free(temp);
}
void display() {
struct Node* temp = head;
while (temp != NULL) {
printf("%d <-> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
int main() {
insertFront(10);
insertEnd(20);
insertFront(5);
insertEnd(25);
display();
deleteLast();
display();
deleteBeforePosition(3);
display();
return 0;
}
Why Use a Doubly Linked List in C?
Using a doubly linked list in C gives you better control over list traversal and simplifies certain operations like reverse traversal or deleting a node before a certain position. This implementation is fundamental in understanding data structures and memory handling in system-level programming.