In a singly linked list each node knows only the node after it, so going backwards or deleting a node means walking from the head to find its predecessor. A doubly linked list gives every node a second pointer, prev, to the node before it. That small extra cost in memory lets you traverse in both directions and insert or remove any node in constant time once you hold a pointer to it. Browser history, music playlists and undo/redo stacks all use this idea.
In this lesson you will learn
- The structure of a doubly linked list node
- Keeping both
headandtailpointers - Inserting at the front, at the back and after any node
- Removing any node in O(1)
- When to choose a doubly linked list
You should already know the singly linked list and malloc and free.
Building and Traversing the List
#include <stdio.h>
#include <stdlib.h>
/* A node with links in both directions */
struct Node {
int data;
struct Node *prev, *next;
};
struct List {
struct Node *head, *tail;
int size;
};
static struct Node *new_node(int value) {
struct Node *n = malloc(sizeof *n);
if (n == NULL) { perror("malloc"); exit(1); }
n->data = value;
n->prev = n->next = NULL;
return n;
}
void push_front(struct List *l, int value) {
struct Node *n = new_node(value);
n->next = l->head;
if (l->head) l->head->prev = n; else l->tail = n;
l->head = n;
l->size++;
}
void push_back(struct List *l, int value) {
struct Node *n = new_node(value);
n->prev = l->tail;
if (l->tail) l->tail->next = n; else l->head = n;
l->tail = n;
l->size++;
}
void print_forward(const struct List *l) {
printf("Forward : NULL <-> ");
for (const struct Node *p = l->head; p; p = p->next) printf("%d <-> ", p->data);
printf("NULL (size %d)\n", l->size);
}
void print_backward(const struct List *l) {
printf("Backward: ");
for (const struct Node *p = l->tail; p; p = p->prev) printf("%d ", p->data);
printf("\n");
}
int main(void) {
struct List list = { NULL, NULL, 0 };
push_back(&list, 20);
push_back(&list, 30);
push_front(&list, 10);
push_back(&list, 40);
print_forward(&list);
print_backward(&list);
/* free every node */
struct Node *p = list.head;
while (p) { struct Node *next = p->next; free(p); p = next; }
return 0;
}
Output
Forward : NULL <-> 10 <-> 20 <-> 30 <-> 40 <-> NULL (size 4)
Backward: 40 30 20 10
- Each
struct Nodestores its value plusprevandnext. The first node’sprevand the last node’snextareNULL. struct Listkeepshead,tailandsizetogether, so adding at either end is O(1) without walking the list.push_frontlinks the new node in front of the old head. If the list was empty, the new node is also the tail.push_backis the mirror image, usingtail.- Because every node knows its predecessor,
print_backwardcan start at the tail and followprevpointers. - Every node created with
mallocis released withfree; the loop savesnextbefore freeing the current node.
Inserting and Deleting Anywhere
#include <stdio.h>
#include <stdlib.h>
struct Node { int data; struct Node *prev, *next; };
struct List { struct Node *head, *tail; int size; };
static void push_back(struct List *l, int v) {
struct Node *n = malloc(sizeof *n);
if (!n) exit(1);
n->data = v; n->next = NULL; n->prev = l->tail;
if (l->tail) l->tail->next = n; else l->head = n;
l->tail = n; l->size++;
}
/* Insert value after node p in O(1) */
void insert_after(struct List *l, struct Node *p, int v) {
struct Node *n = malloc(sizeof *n);
if (!n) exit(1);
n->data = v;
n->prev = p;
n->next = p->next;
if (p->next) p->next->prev = n; else l->tail = n;
p->next = n;
l->size++;
}
/* Unlink and free node p in O(1): no need to search for the previous node */
void remove_node(struct List *l, struct Node *p) {
if (p->prev) p->prev->next = p->next; else l->head = p->next;
if (p->next) p->next->prev = p->prev; else l->tail = p->prev;
free(p);
l->size--;
}
static void show(const char *label, const struct List *l) {
printf("%-22s", label);
for (struct Node *p = l->head; p; p = p->next) printf("%d ", p->data);
printf("| head=%d tail=%d size=%d\n", l->head ? l->head->data : -1,
l->tail ? l->tail->data : -1, l->size);
}
int main(void) {
struct List l = { NULL, NULL, 0 };
for (int v = 1; v <= 5; v++) push_back(&l, v * 10);
show("Start:", &l);
insert_after(&l, l.head->next, 25); /* after 20 */
show("Insert 25 after 20:", &l);
remove_node(&l, l.head); /* remove first */
show("Remove head:", &l);
remove_node(&l, l.tail); /* remove last */
show("Remove tail:", &l);
remove_node(&l, l.head->next); /* remove 25 from the middle */
show("Remove middle (25):", &l);
while (l.head) remove_node(&l, l.head);
show("After clearing:", &l);
return 0;
}
Output
Start: 10 20 30 40 50 | head=10 tail=50 size=5
Insert 25 after 20: 10 20 25 30 40 50 | head=10 tail=50 size=6
Remove head: 20 25 30 40 50 | head=20 tail=50 size=5
Remove tail: 20 25 30 40 | head=20 tail=40 size=4
Remove middle (25): 20 30 40 | head=20 tail=40 size=3
After clearing: | head=-1 tail=-1 size=0
insert_afterrewires four pointers: the new node’sprevandnext, the old next node’sprev, andp->next. Ifpwas the tail, the new node becomes the tail.remove_nodejoins the neighbours directly to each other. In a singly linked list you would need an O(n) search to find the previous node; herep->prevgives it immediately.- The two
if ... elsechecks handle the special cases of removing the head or the tail, which is where most linked-list bugs hide. - After clearing, both
headandtailareNULLandsizeis 0, which the output confirms with -1 placeholders.
Singly vs Doubly Linked List
| Operation | Singly (with tail) | Doubly |
|---|---|---|
| Insert at front / back | O(1) / O(1) | O(1) / O(1) |
| Delete the head | O(1) | O(1) |
| Delete the tail | O(n), must find the node before it | O(1) |
| Delete a given node | O(n) | O(1) |
| Traverse backwards | Not possible directly | Yes |
| Extra memory per node | One pointer | Two pointers |
A doubly linked list combined with a hash table that maps keys to nodes is the classic way to build an LRU (least recently used) cache, where both lookup and “move to front” are O(1).
Common Mistakes
- Updating only one direction, so
nextandprevdisagree and backward traversal breaks. - Forgetting to update
headortailwhen inserting into an empty list or removing an end node. - Using a node after
free, for example readingp->nextafter freeingp. - Not keeping
sizein sync with insertions and deletions.
Practice Exercises
Exercise 1. Write reverse(struct List *l) that reverses the list in place.
Show answer
void reverse(struct List *l) {
struct Node *p = l->head;
while (p) { /* swap prev and next in every node */
struct Node *t = p->next;
p->next = p->prev;
p->prev = t;
p = t;
}
struct Node *t = l->head; l->head = l->tail; l->tail = t;
}
Exercise 2. Write pop_back that removes the last node and returns its value.
Show answer
int pop_back(struct List *l) { /* assumes the list is not empty */
int v = l->tail->data;
remove_node(l, l->tail);
return v;
}
Frequently Asked Questions
What is a circular doubly linked list?
The last node’s next points back to the first node and the first node’s prev points to the last, so there are no NULL ends. It is handy for round-robin scheduling and playlists that repeat.
Is a doubly linked list faster than an array?
Only for inserting and deleting in the middle when you already hold a pointer to the node. Arrays are faster for indexing and for scanning, because their elements sit next to each other in memory.
Summary
- Each node has
prevandnextpointers. - Head and tail pointers make both ends O(1).
- Any node can be removed in O(1) without searching.
- Always update both directions and the head/tail special cases.
