Reading history

Doubly Linked List in C: Insert, Delete and Traverse

7 min read 0 views

Learn the doubly linked list in C: nodes with prev and next pointers, head and tail, inserting and deleting any node in O(1), and backward traversal.

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 head and tail pointers
  • 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 Node stores its value plus prev and next. The first node’s prev and the last node’s next are NULL.
  • struct List keeps head, tail and size together, so adding at either end is O(1) without walking the list.
  • push_front links the new node in front of the old head. If the list was empty, the new node is also the tail.
  • push_back is the mirror image, using tail.
  • Because every node knows its predecessor, print_backward can start at the tail and follow prev pointers.
  • Every node created with malloc is released with free; the loop saves next before 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_after rewires four pointers: the new node’s prev and next, the old next node’s prev, and p->next. If p was the tail, the new node becomes the tail.
  • remove_node joins the neighbours directly to each other. In a singly linked list you would need an O(n) search to find the previous node; here p->prev gives it immediately.
  • The two if ... else checks handle the special cases of removing the head or the tail, which is where most linked-list bugs hide.
  • After clearing, both head and tail are NULL and size is 0, which the output confirms with -1 placeholders.

Singly vs Doubly Linked List

OperationSingly (with tail)Doubly
Insert at front / backO(1) / O(1)O(1) / O(1)
Delete the headO(1)O(1)
Delete the tailO(n), must find the node before itO(1)
Delete a given nodeO(n)O(1)
Traverse backwardsNot possible directlyYes
Extra memory per nodeOne pointerTwo 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

  1. Updating only one direction, so next and prev disagree and backward traversal breaks.
  2. Forgetting to update head or tail when inserting into an empty list or removing an end node.
  3. Using a node after free, for example reading p->next after freeing p.
  4. Not keeping size in 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 prev and next pointers.
  • 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.

Next: Circular Queue and Deque in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *