AlgoViz

Doubly linked list

easy 16 min

A doubly linked list is a chain of nodes where every node links to both its neighbours, the one before (prev) and the one after (next).

Video lesson · Chapter 1 of 6

The return trip

0:00 / 4:51

Doubly linked lists — The missing tram car

1:26Reel

Read caption

Vera unlinks car B from a four-car tram by repairing both directions of the route. Two neighbors, two repairs.

How it works

Step through the idea, or press Play.

Step 1 of 3

Link both ways. Every node stores a value, a next pointer forward and a prev pointer back

Understand it

Start here

What a doubly linked list is

A doubly linked list (DLL) is a singly linked list where every node also remembers the node behind it. Each node holds three things: the data, a next pointer to the node ahead and a prev pointer to the node behind. The list keeps a head pointer to the first node and a tail pointer to the last, and both ends finish at None.

  • Two links per node

    next looks ahead, prev looks back. Every node knows both neighbours.

  • Two entry points

    head and tail let you start at either end without walking.

  • Walk either way

    Follow next from the head, or prev from the tail. A singly linked list can only go forward.

Python
class Node:    def __init__(self, val):        self.val = val        self.prev = None   # who is behind me?        self.next = None   # who is ahead of me?a, b = Node(10), Node(20)a.next, b.prev = b, a      # link both directionsprint(a.next.val, b.prev.val)   # 20 10
The whole idea fits in one class: a value and two links.
Edit and run it in your browser

The picture

Two-way links in one picture

A doubly linked list of 10, 20, 30

Each arrow between nodes is really two pointers: one forward, one back. Both ends stop at NULL.

The invariant every operation must keep

x.next≠None  ⇒  x.next.prev=xandhead.prev=tail.next=Nonex.\text{next} \neq \text{None} \;\Rightarrow\; x.\text{next}.\text{prev} = x \qquad\text{and}\qquad \text{head}.\text{prev} = \text{tail}.\text{next} = \text{None}
Walk forward one step and back one step and you must land where you started. Every bug in a doubly linked list breaks this rule somewhere.

The API

Core operations

OperationWhat it doesOn 10 ⇄ 20 ⇄ 30 ⇄ 40Time
insert_head(x)Links a new node before the head and moves headinsert_head(5) gives 5 ⇄ 10 ⇄ 20 ⇄ 30 ⇄ 40O(1)O(1)
insert_tail(x)Links a new node after the tail and moves tailinsert_tail(50) gives 10 ⇄ … ⇄ 40 ⇄ 50O(1)O(1)
delete_head()Moves head to head.next and clears its prevreturns 10, leaves 20 ⇄ 30 ⇄ 40O(1)O(1)
delete_tail()Moves tail to tail.prev and clears its nextreturns 40, leaves 10 ⇄ 20 ⇄ 30O(1)O(1)
delete_at(i)Walks to index i, then links its neighbours to each otherdelete_at(1) removes 20O(n)O(n) walk, O(1)O(1) unlink
traverse_forward()Head to tail along next10, 20, 30, 40O(n)O(n)
traverse_backward()Tail to head along prev40, 30, 20, 10O(n)O(n)
search(x)Checks nodes one by one from either endsearch(30) returns index 2O(n)O(n)
These are exactly the operations the visualizer steps through, one pointer change at a time.

Notice the split: anything at an end is O(1)O(1) because a pointer already sits there. Anything that needs a position or a value is O(n)O(n) because the nodes are scattered in memory and must be reached hop by hop.

Under the hood

Inserting at either end

insert_head(x)

Two links are made before head moves. The empty case must also set tail.

insert_tail(x)

The mirror image of insert_head. With the tail pointer there is no walk, so it is O(1)O(1).
Python
class Node:    def __init__(self, val):        self.val, self.prev, self.next = val, None, Nonedef insert_after(node, val):    new = Node(val)    new.prev = node          # 1. new looks back at node    new.next = node.next     # 2. new looks ahead at node's old next    if node.next:        node.next.prev = new # 3. old next looks back at new    node.next = new          # 4. node looks ahead at new    return newa = Node(10); c = Node(30)a.next, c.prev = c, ainsert_after(a, 20)print(a.next.val, c.prev.val)   # 20 20
Inserting after a node you already hold takes four pointer writes, in this order.
Edit and run it in your browser

Under the hood

Deleting from the ends and the middle

delete_tail(): the O(1) advantage

delete_head() is the same path with head, next and prev swapped.

Why the prev pointer matters for the tail

n−2 hops⏟singly: find the second-to-last node=O(n)vstail.prev⏟doubly: one read=O(1)\underbrace{n - 2 \text{ hops}}_{\text{singly: find the second-to-last node}} = O(n) \qquad\text{vs}\qquad \underbrace{\text{tail.prev}}_{\text{doubly: one read}} = O(1)
A singly linked list knows its tail but not the node before it, so removing the tail means walking from the head. A doubly linked list reads tail.prev directly.

Unlinking any node you hold

Two pointer writes bypass the node. A singly linked list cannot do this without first finding the previous node in O(n)O(n).

Both directions

Traversal and search

Forward traversal starts at head and follows next until None. Backward traversal starts at tail and follows prev until None, something a singly linked list can only fake by reversing itself first. Search is a traversal that stops early, and because you can start at either end, reaching index ii only needs the shorter walk.

Reach index i from the closer end

The closer end halves the walk, but it is still linear

hops(i)=min⁡(i,  n−1−i)  ≤  ⌊n−12⌋  =  O(n)\text{hops}(i) = \min(i,\; n - 1 - i) \;\le\; \left\lfloor \frac{n - 1}{2} \right\rfloor \;=\; O(n)
In a list of n=9n = 9 the worst case is the middle, index 4, at 4 hops instead of 8. Halving a linear cost is still linear.
Python
class Node:    def __init__(self, val):        self.val, self.prev, self.next = val, None, Nonenodes = [Node(v) for v in [10, 20, 30, 40]]for a, b in zip(nodes, nodes[1:]):    a.next, b.prev = b, ahead, tail = nodes[0], nodes[-1]forward, cur = [], headwhile cur:    forward.append(cur.val)    cur = cur.nextbackward, cur = [], tailwhile cur:    backward.append(cur.val)    cur = cur.prevprint(forward)    # [10, 20, 30, 40]print(backward)   # [40, 30, 20, 10]
Walk the same list both ways.
Edit and run it in your browser

Complexity

What each operation costs

OperationTimeSpaceWhy
Insert or delete at headO(1)O(1)O(1)O(1)The head pointer is already there
Insert or delete at tailO(1)O(1)O(1)O(1)The tail pointer is there, and tail.prev gives the new tail
Unlink a node you holdO(1)O(1)O(1)O(1)Both neighbours are one hop away
Insert or delete at indexO(n)O(n)O(1)O(1)Walking to the index dominates; the splice itself is O(1)O(1)
Access by indexO(n)O(n)O(1)O(1)At most about n/2n/2 hops from the closer end
Search by valueO(n)O(n)O(1)O(1)Nodes are checked one by one
Traverse either wayO(n)O(n)O(1)O(1)Visits every node once
The list itselfO(n)O(n)Each node stores a value and two pointers

The memory price of the prev pointer

d+p⏟singly node  →  d+2p⏟doubly noded=p=8 bytes: 16→24 bytes=1.5×\underbrace{d + p}_{\text{singly node}} \;\to\; \underbrace{d + 2p}_{\text{doubly node}} \qquad d = p = 8 \text{ bytes: } 16 \to 24 \text{ bytes} = 1.5\times
Pointer memory doubles (one pointer becomes two), but the whole node grows by one pointer, not by a factor of two. It is still O(n)O(n) space overall.

Comparison

Doubly vs singly vs array

Dynamic arraySingly linked (head + tail)Doubly linked
Access by indexO(1)O(1)O(n)O(n)O(n)O(n), from the closer end
Insert at headO(n)O(n), shifts everythingO(1)O(1)O(1)O(1)
Insert at tailO(1)O(1) amortisedO(1)O(1) with a tail pointerO(1)O(1)
Delete headO(n)O(n)O(1)O(1)O(1)O(1)
Delete tailO(1)O(1)O(n)O(n)O(1)O(1)
Delete a node you holdO(n)O(n), shiftsO(n)O(n), must find the previous nodeO(1)O(1)
Walk backwardYesNoYes
Memory per itemValue onlyValue + 1 pointerValue + 2 pointers
Cache localityExcellentPoorPoor
Code complexitySimplestSimpleMore edge cases
Best fits: dynamic arrays for random access, singly lists for stacks and simple forward chains, doubly lists for LRU caches, history and deques.

Use a doubly linked list when

  • You need O(1)O(1) insert and delete at both ends.
  • You move backward as well as forward: back and forward, previous and next.
  • You must remove a node you already hold in O(1)O(1), as in an LRU cache.
  • You build a deque or an ordered map from scratch.

Do not use one when

  • You only ever walk forward: a singly linked list is lighter.
  • Memory is tight: one pointer per node is cheaper.
  • You need random access by index: use an array.
  • Scan speed and cache locality matter most: use an array.

Implementation

Sentinels and edge cases

  • Empty list

    Check head is None first. Inserting into an empty list sets both head and tail.

  • Single node

    head is tail. Deleting it clears both pointers.

  • Dangling pointers

    Set a removed node's prev and next to None so nothing still reaches it.

  • Sentinel nodes

    A dummy head and a dummy tail that never hold data. Every real node sits between two nodes, so the special cases disappear.

Python
class Node:    def __init__(self, val=None):        self.val, self.prev, self.next = val, None, Noneclass SentinelList:    def __init__(self):        self.front, self.back = Node(), Node()   # dummies, never removed        self.front.next, self.back.prev = self.back, self.front    def _insert_between(self, val, a, b):        node = Node(val)        node.prev, node.next = a, b        a.next = b.prev = node        return node    def push_front(self, val):        return self._insert_between(val, self.front, self.front.next)    def push_back(self, val):        return self._insert_between(val, self.back.prev, self.back)    def remove(self, node):        node.prev.next, node.next.prev = node.next, node.prev        node.prev = node.next = None        return node.val    def items(self):        out, cur = [], self.front.next        while cur is not self.back:            out.append(cur.val)            cur = cur.next        return outlst = SentinelList()lst.push_back(20); lst.push_back(30); n = lst.push_front(10)lst.remove(n)print(lst.items())   # [20, 30]
With two sentinels, insert and remove have no if statements at all.
Edit and run it in your browser

In the wild

Where doubly linked lists run

  • Browser history

    Each page links to the one before (Back) and the one after (Forward).

  • Music playlists

    Previous and Next follow prev and next from the song now playing.

  • Undo and redo

    Each action is a node. Undo steps back along prev, redo steps forward along next.

  • LRU caches

    Databases, browsers and CDNs evict the least recently used entry with a hash map plus a doubly linked list.

  • Window switching

    Alt+Tab cycles through open windows in most-recently-used order.

  • Deques

    Python's collections.deque is a doubly linked list of blocks: O(1)O(1) at both ends.

LRU cache: hash map plus doubly linked list

The map finds a node in O(1)O(1); the prev pointer lets it be unlinked in O(1)O(1). Most recent sits at the front, least recent at the back.

Pattern spotting

Spotting a doubly linked list problem

Should I use a doubly linked list?

  • LRU cache

    Hash map from key to node, list ordered by recency. O(1)O(1) get and put.

  • Design browser history

    Visit inserts after the current page and drops the forward pages; back and forward walk the links.

  • Flatten a multilevel list

    Nodes also have a child pointer; splice each child list in between a node and its next.

  • BST to sorted list

    An in-order walk relinks left and right as prev and next.

  • Deque and All O(1)

    Double-ended queues, and count buckets kept in order for O(1)O(1) increment, decrement, min and max.

Related structures: a circular doubly linked list joins tail.next to head and head.prev to tail, so traversal stops when you return to the start rather than at None. A deque, the double-ended cousin of the queue, is the abstract type a doubly linked list implements naturally. A skip list stacks several linked levels to search in O(log⁡n)O(\log n) expected time.

Recap

Key takeaways

Key points

  • Each node stores a value, next and prev; the list keeps head and tail, and both ends stop at None.
  • Insert and delete at either end are O(1)O(1). Deleting the tail is O(1)O(1) here and O(n)O(n) in a singly linked list.
  • Unlinking a node you hold is O(1)O(1); finding a position or value is O(n)O(n), at most about n/2n/2 hops from the closer end.
  • The price is one extra pointer per node and more edge cases; space is still O(n)O(n).
  • Link the new node first, move head or tail last, and clear both pointers when the last node goes.
  • Sentinel nodes remove the empty and end special cases.
  • LRU cache = hash map + doubly linked list. Browser history, playlists and undo and redo all walk both ways.

Sources