Skip to content
Visual explainer 2h 30m to learn 4 steps

Doubly linked & circular lists

Use doubly linked and circular lists and detect cycles with fast and slow pointers.

By Invicly Tech, , in Data Structures & Algorithms. About 11 minutes to read.

Topic 11 of 54

In short

A doubly linked list gives each node both next and prev pointers, so a node can be removed in O(1) when you already hold a reference to it. Circular lists link the tail back to the head. Fast and slow pointer techniques find midpoints and detect cycles without extra memory.

Explained simply

A doubly linked list is a linked list where every node has two arrows: one to the next node and one back to the previous node. That extra arrow costs a little memory, but now you can walk in both directions.

The big win is removal. In a singly linked list, to remove a node you first need the node before it, which may mean walking from the head. In a doubly linked list the node already knows its neighbours, so you can unlink it in a few steps, no matter how long the list is.

In a circular list, the last node does not point to nothing. It points back to the first node, so the chain becomes a ring. That is handy for things that take turns forever, like players in a game or tasks in a round-robin scheduler.

Sometimes a ring appears by accident, from a bug. Then a simple loop over the list never ends. The fast and slow pointer trick, also called Floyd's algorithm, detects such a loop using only two variables.

Press Play on a diagram to walk through it one step at a time.

CycleFloyd's cycle detection
  1. 1
    Start

    slow and fast at head.

  2. 2
    Move

    slow 1 step, fast 2 steps.

  3. 3
    Compare

    Meet means a cycle exists.

  4. 4
    Repeat

    fast reaching None means no cycle.

  5. Back to step 1
CompareSingly, doubly and circular lists
Singly linked
  • One pointer per node
  • Remove a node: needs its predecessor
  • Walk forward only
  • Ends at None
Doubly linked
  • Two pointers per node
  • Remove a held node: O(1)
  • Walk both ways
  • Sentinels remove edge cases
Circular
  • Tail points back to head
  • No None to stop at
  • Good for round-robin turns
  • Tail pointer gives O(1) at both ends

In depth

Sentinels: no more None checks

A plain doubly linked list has many edge cases: inserting into an empty list, removing the only node, changing the head or the tail. Each needs its own if statement, and each is a place for bugs.

Sentinels remove them. Create two permanent dummy nodes, head and tail, linked to each other at the start. Real nodes always live between them. Now every real node has a real prev and a real next, so insert after any node and remove any node are each one short block of code with no conditions. The list is empty when head.next is tail.

Inserting X after node A changes four pointers: X.prev = A, X.next = A.next, A.next.prev = X, A.next = X. Removing node X changes two: X.prev.next = X.next and X.next.prev = X.prev. Both are O(1). Always set the new node's own pointers first, then update the neighbours.

FlowRemoving node B from A <-> B <-> C
  1. Step 1
    Hold B

    From a hash map or a previous step

  2. Step 2
    Bypass forward

    B.prev.next = B.next, so A -> C

  3. Step 3
    Bypass backward

    B.next.prev = B.prev, so A <- C

  4. Step 4
    Done in O(1)

    B is detached; no walk from the head

Circular lists in practice

In a circular singly linked list the tail points to the head. A neat trick is to keep only a pointer to the tail: then the head is tail.next, so you can insert at both the front and the back in O(1).

The danger is traversal. A loop that stops at None never ends, because there is no None. Instead, stop when you come back to the node you started from, using a do-while style: process the start node, move on, and continue until cur is start again.

Circular structures appear in round-robin scheduling (each task gets a turn, then the pointer moves on), in the Josephus problem, and in ring buffers, which are the array version of the same idea and come up in the next topic. A doubly circular list with one sentinel, whose next is the first node and whose prev is the last, is how many standard libraries implement their linked lists.

  • Keep a tail pointer: head is tail.next
  • Stop traversal when you return to the start node
  • Rotate a list: make it circular, then cut at the new tail

Floyd's algorithm, phase two: where does the cycle start?

Phase one (fast moves 2, slow moves 1) tells you whether a cycle exists. Phase two finds the node where it begins. After they meet, put one pointer back at the head and move both one step at a time. The node where they meet again is the start of the cycle.

Why? Let a be the distance from the head to the cycle start, b the distance from the start to the meeting point, and c the cycle length. When they meet, slow has walked a + b and fast twice that. Fast's extra distance a + b is a whole number of laps, so a + b = k times c. That means a = k times c minus b: walking a steps from the meeting point lands exactly on the cycle start, which is also a steps from the head.

To get the cycle length, keep one pointer at the meeting point and count steps until the other returns. Everything stays O(n) time and O(1) space.

FlowFinding the start of a cycle
  1. 1
    Phase 1

    slow +1, fast +2 until they meet

  2. 2
    No meeting?

    fast hit None: there is no cycle

  3. 3
    Reset

    Move slow back to head; fast stays

  4. 4
    Phase 2

    Both move +1 per step

  5. 5
    Meet again

    That node is where the cycle starts

Middle of the list: first or second middle?

With slow moving 1 and fast moving 2, slow is at the middle when fast runs out. For an odd length there is one middle. For an even length there are two, and the loop condition decides which one you get.

With while fast and fast.next, slow stops on the second middle: for 1 2 3 4 it returns 3. With while fast.next and fast.next.next (and a non-empty list), slow stops on the first middle, 2. The first middle is what you want when splitting a list for merge sort, because you then cut after slow and both halves are non-empty for any list of two or more nodes.

The same idea gives other positions too: a fast pointer moving 3 steps finds the node one third of the way in.

  • while fast and fast.next: second middle
  • while fast.next and fast.next.next: first middle
  • Merge sort splits after the first middle

Learn it in 4 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Implement a doubly linked list with sentinels~40m
  2. 2
    Remove a node in O(1)~40m
  3. 3
    Detect cycles with Floyd's algorithm~40m
  4. 4
    Find the middle with fast and slow pointers~40m

Key points

  • Remove a known node in a doubly linked list: O(1).
  • Sentinel head and tail nodes remove all null checks.
  • Floyd's algorithm detects a cycle in O(n) time and O(1) space.
  • An LRU cache combines a hash map with a doubly linked list for O(1) get and put.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
def has_cycle(head):              # O(n) time, O(1) space
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:
            return True
    return False

def middle(head):
    slow = fast = head
    while fast and fast.next:
        slow, fast = slow.next, fast.next.next
    return slow

A doubly linked list with two sentinels

Goal: a list where insert_after and remove are O(1) with no if statements. Step 1: create the head and tail sentinels and link them to each other. Step 2: insert_after sets the new node's pointers first, then makes both neighbours point at it. Step 3: remove makes the two neighbours point at each other. This is the core of an LRU cache, where a dict maps keys to these nodes.

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

class DList:
    def __init__(self):
        self.head, self.tail = DNode(), DNode()      # sentinels
        self.head.next, self.tail.prev = self.tail, self.head
    def insert_after(self, node, val):               # O(1)
        new = DNode(val)
        new.prev, new.next = node, node.next
        node.next.prev = new
        node.next = new
        return new
    def remove(self, node):                          # O(1)
        node.prev.next, node.next.prev = node.next, node.prev

Find the node where a cycle begins

A list 3 -> 2 -> 0 -> -4 whose last node points back to 2. Step 1: run slow and fast until they meet inside the cycle; if fast reaches None, return None. Step 2: move slow back to the head. Step 3: advance both by one; they meet at node 2, the cycle start. The while-else runs the else branch only if the loop ended without break, which means no cycle. O(n) time, O(1) space.

python
def cycle_start(head):
    slow = fast = head
    while fast and fast.next:
        slow, fast = slow.next, fast.next.next
        if slow is fast:
            break
    else:
        return None               # fast reached the end: no cycle
    slow = head
    while slow is not fast:
        slow, fast = slow.next, fast.next
    return slow

Quick reference

  • Doubly linked remove of a held node: X.prev.next = X.next; X.next.prev = X.prev (O(1))
  • Insert after A: set new.prev and new.next first, then A.next.prev and A.next
  • Sentinels: list is empty when head.next is tail
  • Floyd phase 1 detects a cycle; phase 2 (reset one pointer to head) finds its start
  • while fast and fast.next stops slow on the second middle of an even list
  • Circular traversal: stop when cur returns to the start node, not at None
  • LRU cache = dict of key to node + doubly linked list ordered by recent use

Common mistakes

  • Updating only one of the two pointers when unlinking a node.
  • Checking fast.next.next without first checking fast.next.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1After Floyd's pointers meet, one is reset to the head and both move one step at a time. Where do they meet next?

Question 2

2How many pointer assignments does removing a node from a doubly linked list with sentinels need?

Question 3

3For the list 1 2 3 4, where does slow stop with the loop while fast and fast.next?

Question 4

4Why can a loop like while cur: cur = cur.next run forever on a circular list?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Count the nodes of a circular singly linked list, given any node in it.

  2. Exercise 2medium

    Rotate a singly linked list to the right by k places (1 2 3 4 5 with k = 2 becomes 4 5 1 2 3) in O(n).

  3. Exercise 3hard

    Build an LRU cache with get(key) and put(key, value), both O(1), that evicts the least recently used key when over capacity.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is a doubly linked list always better than a singly linked one?
No. It uses an extra pointer per node and more pointer updates per change. Use it when you need O(1) removal of held nodes or backward traversal.
Can I detect a cycle with a set instead of Floyd's algorithm?
Yes: store each visited node in a set and stop when you see one twice. That is O(n) time but O(n) extra space, while Floyd's uses O(1).
How does Python's OrderedDict keep its order?
Besides the hash table, OrderedDict keeps its keys in a doubly linked list, which makes move_to_end and popitem at either end O(1). That is why it is a quick way to build an LRU cache.

Go deeper

ShareXLinkedInWhatsApp