Lesson 10 · Linear structures

Doubly Linked Lists

A doubly linked list is a chain of nodes where each node links to both its successor and its predecessor. The extra prev link costs one pointer per node and buys O(1) deletion of a node you already hold and traversal in both directions.

Doubly Linked Lists concept diagramA visual explanation of the layout and operations shown in this lesson.next moves forward · prev moves backwardhead10203040nullevery node stores both a next and a prev link
1

Nodes With Two Links

A doubly linked list is a linear data structure made of nodes, where each node holds a value and two pointers: next to the node after it and prev to the node before it. The list keeps a head reference and usually a tail reference, so both ends are reachable in O(1).

Because the links go both ways, you can walk the list forward from the head, backward from the tail, or in either direction from any node you hold.

The first node's prev and the last node's next are null (NULL in C, nullptr in C++, None in Python). Those nulls mark the ends, and forgetting to set them is the most common structural bug.

The price is one extra pointer per node, 8 bytes on a 64-bit machine. For a list of small integers the two pointers can take more space than the data.

  • Node = value + next + prev
  • head.prev and tail.next are null
  • Like any linked list, reaching position k still takes O(k) steps
2

Insertion in a Doubly Linked List

  1. X.prev = A
  2. X.next = B
  3. A.next = X
  4. B.prev = X

Putting a new node X between neighbours A and B takes the four writes above, in that order. The first two touch only the new node, so the list is still intact if anything goes wrong before step 3.

The classic bug is changing A.next first. Once A.next = X has run, A.next no longer leads to B, so X.next = A.next makes X point to itself and every node after it is lost: a leak in C and C++, silent data loss elsewhere.

At the head, there is no A: set X.next = head and X.prev = null, then head.prev = X if the list was not empty, then head = X. If the list was empty, tail must also become X. At the tail it is the mirror image, and it is O(1) only because the list keeps a tail reference.

Inserting at position k costs O(k) to walk there; the rewiring itself is always O(1).

  • New node's links first, neighbours' links second
  • An insert into an empty list sets both head and tail
3

Deletion in a Doubly Linked List

Given the node X to remove, two writes unlink it: X.prev.next = X.next and X.next.prev = X.prev. No traversal is needed, so deletion is O(1) once you hold the node.

A singly linked list cannot do this. It must change the predecessor's next, and the only way to find the predecessor is to walk from the head, which is O(n). That difference is the reason the prev pointer exists.

The ends need care because one neighbour may be null. If X.prev is null, X was the head, so set head = X.next. If X.next is null, X was the tail, so set tail = X.prev. Deleting the only node sets both to null.

Forgetting the second write is the bug to watch for. The list then prints correctly from the head, but walking back from the tail reaches the deleted node again. Testing only the forward direction never catches it.

In C and C++, free the node afterwards (free(X), delete X). In Java and Python the garbage collector reclaims it once nothing refers to it, which is why clearing the deleted node's own prev and next is good practice.

Deleting a node when you already hold a reference to it
List typeFind predecessorRewireTotal
Singly linkedO(n) traversalO(1)O(n)
Doubly linkedO(1) via prevO(1)O(1)
  • X.prev.next = X.next; X.next.prev = X.prev
  • Null prev means X was the head; null next means it was the tail
  • Print the list backward as well as forward when testing
Key reference

Terms, operations, and practical uses

Pointer mechanics

  • Previous Pointer (prev)An additional reference in every node that points to the node immediately behind it.
  • Bidirectional TraversalThe ability to walk the list backward from tail to head, impossible in a singly linked list.
  • O(1) DeletionRemoving a node instantly if you hold a reference to it, by bridging its prev and next nodes together.

Structure management

  • Tail PointerA reference to the very last node, allowing O(1) insertions at the end and backward traversal.
  • Sentinel NodesUsing both a dummy head and dummy tail to ensure every real node has a non-null prev and next, eliminating edge cases.
  • Pointer ReassignmentThe complex process of updating four different pointers to safely insert a node between two others.

Real-world uses

  • LRU CacheLeast Recently Used cache. Combines a hash map with a doubly linked list to evict the oldest item in O(1) time.
  • Browser HistoryStoring web pages so the user can freely step backward and forward through their visited sites.
  • Undo/Redo BuffersAllowing users to traverse backward through their action history, and forward if they redo.
Implementation

Code in Python, C++ and Java

class Node:
    def __init__(self, val):
        self.val = val
        self.prev = None
        self.next = None

# Build 10 <-> 20 <-> 30 <-> 40 <-> 50
head = Node(10)
node = head
for value in (20, 30, 40, 50):
    node.next = Node(value)
    node.next.prev = node
    node = node.next

def delete(node):
    # The node itself is enough: prev is right there.
    if node.prev:
        node.prev.next = node.next
    if node.next:
        node.next.prev = node.prev
    node.prev = node.next = None

target = head.next.next          # the node holding 30
delete(target)

forward = []
node = head
while node:
    forward.append(node.val)
    tail = node
    node = node.next

backward = []
node = tail
while node:
    backward.append(node.val)
    node = node.prev

print(' <-> '.join(map(str, forward)), '(forward)')
print(' <-> '.join(map(str, backward)), '(backward)')
#include <iostream>
using namespace std;

struct Node {
    int val;
    Node* prev;
    Node* next;
    Node(int x) : val(x), prev(NULL), next(NULL) {}
};

void deleteNode(Node* node) {
    if (node->prev) {
        node->prev->next = node->next;
    }
    if (node->next) {
        node->next->prev = node->prev;
    }
    delete node;
}

int main() {
    Node* head = new Node(10);
    Node* node = head;
    int values[] = {20, 30, 40, 50};
    for (int i = 0; i < 4; i++) {
        node->next = new Node(values[i]);
        node->next->prev = node;
        node = node->next;
    }
    Node* tail = node;

    Node* target = head->next->next;   // the node holding 30
    deleteNode(target);

    for (Node* p = head; p != NULL; p = p->next) {
        cout << p->val;
        if (p->next) cout << " <-> ";
    }
    cout << " (forward)\n";
    for (Node* p = tail; p != NULL; p = p->prev) {
        cout << p->val;
        if (p->prev) cout << " <-> ";
    }
    cout << " (backward)\n";
}
class Main {
    static class Node {
        int val;
        Node prev;
        Node next;
        Node(int x) { val = x; }
    }

    static void delete(Node node) {
        if (node.prev != null) {
            node.prev.next = node.next;
        }
        if (node.next != null) {
            node.next.prev = node.prev;
        }
        node.prev = null;
        node.next = null;
    }

    public static void main(String[] args) {
        Node head = new Node(10);
        Node node = head;
        int[] values = {20, 30, 40, 50};
        for (int i = 0; i < values.length; i++) {
            node.next = new Node(values[i]);
            node.next.prev = node;
            node = node.next;
        }
        Node tail = node;

        Node target = head.next.next;   // the node holding 30
        delete(target);

        StringBuilder forward = new StringBuilder();
        for (Node p = head; p != null; p = p.next) {
            forward.append(p.val);
            if (p.next != null) forward.append(" <-> ");
        }
        System.out.println(forward + " (forward)");

        StringBuilder backward = new StringBuilder();
        for (Node p = tail; p != null; p = p.prev) {
            backward.append(p.val);
            if (p.prev != null) backward.append(" <-> ");
        }
        System.out.println(backward + " (backward)");
    }
}
Watch it run

Step through it

Running on 10 ⇄ 20 ⇄ 30 ⇄ 40 ⇄ 50, delete the node holding 30

10 ⇄ 20 ⇄ 30 ⇄ 40 ⇄ 50prevnext10∅head20304050∅tailforward: 10 20 30 40 50 · backward: 50 40 30 20 10
Step 1

Five nodes, two chains

Each node holds a value and two links: next to its successor and prev to its predecessor. The top arrows are the forward chain, the bottom arrows the backward chain. head.prev and tail.next are null (∅): that is how the code knows it has reached an end.

Output
1 / 11
4

Sentinel Nodes

The null checks in insert and delete exist only for the ends of the list. A sentinel (dummy) node at each end removes them: the real nodes always sit between a dummy head and a dummy tail, so every real node has a non-null prev and next.

With sentinels, delete is always the same two writes and insert the same four, whether the node is first, last or in the middle. An empty list is just the two sentinels pointing at each other. The cost is two extra nodes per list, which is why most library implementations and LRU cache solutions use them.

  • Dummy head and tail hold no data
  • Removes every if from insert and delete
5

Singly vs Doubly Linked List

Choose a doubly linked list when you need to remove nodes you already hold, or to move in both directions. Choose a singly linked list when you only walk forward and memory per node matters, as in a stack or a hash table bucket.

Singly vs doubly linked list
Singly linkedDoubly linked
Pointers per node1 (next)2 (next, prev)
Delete a node you holdO(n), must find the predecessorO(1)
Insert before a node you holdO(n)O(1)
Walk backwardNot possibleYes, from the tail or any node
Writes per insert24
  • Doubly: O(1) delete and backward walks, one more pointer per node
  • Singly: smaller and simpler when you only go forward
6

Applications of Doubly Linked List

LRU cache. A cache that evicts the least recently used entry needs O(1) lookup and O(1) reordering. A hash map from key to node gives the lookup; a doubly linked list ordered by recency gives the reordering. On each access the node is unlinked with its own prev and next and moved to the front; on overflow the node before the tail sentinel is evicted. The LRU Cache problem is exactly this design.

Library containers. Java's LinkedList and LinkedHashMap, C++'s std::list and Python's collections.OrderedDict all keep their order in one. Python's deque is a doubly linked list of fixed-size blocks.

Back and forward navigation. Browser history and undo/redo step backward and forward through the same chain of states. The Linux kernel's list_head, used across the kernel, is a circular doubly linked list. Problems such as Flatten a Multilevel Doubly Linked List practise the pointer handling. For a list whose ends join, see circular linked lists.

  • Hash map + doubly linked list = O(1) LRU cache
  • Ordered maps and deques in Java, C++ and Python
  • Anything that steps both back and forward