# linked list

> nodes that each point to the next. cheap to splice in, slow to index.

source: https://learning.anthnydas.com/ds/linked-list/

## tl;dr

nodes scattered in memory, each holding a value and an arrow to the next. the list only keeps the head.

- **push / pop front:** O(1) (one arrow changes)
- **insert / remove after a node you hold:** O(1) (an arrow or two change, nothing slides)
- **get(i):** O(i) (walk from the head, no jumping)
- **push back:** O(n) (without a tail pointer, a walk to the end)
- **reach for it:** stacks and queues (with a tail pointer), lists you splice into a lot, the chains in a hash table, lru caches (doubly linked)

a linked list keeps each item in its own node: the value, and an arrow to the next node. the nodes can sit anywhere in memory, and the list itself holds only the arrow to the first one, the head. nothing ever slides over, because there's no row to keep in order, only arrows. the price is that there's no jumping to item i: you follow the arrows from the head.

## the idea

> **interactive figure:** an animation in six steps. four nodes, 4, 8, 15 and 16, sit scattered around memory, each with an arrow to the next, and a head box points at 4. they line up in order. a new node 2 appears, points at 4, and the head moves to it. then 8 is removed: an arc from 4 jumps over it to 15, and 8 lifts away. then reverse: 2's arrow goes to null, and one by one 4, 15 and 16 point back at the node before them, until the head moves to 16. last, the nodes are redrawn in the new order, 16, 15, 4, 2, arrows pointing right again.

nodes sit wherever they were allocated, each pointing at the next. the list only holds the head.

the same list, drawn in order. the arrows don't change, only where we put the boxes.

push to the front: the new node points at the old head, then the head moves to it. no other node is touched.

remove 8: the node before it, 4, points past it to 15. 8 is cut out of the chain. the rest is redrawn closer, but nothing moved in memory.

reverse: walk the list once. each node's arrow turns to point at the node before it, and the first one points at null. then the head moves to the old end.

drawn front to back again: the same nodes, the chain backwards.

## the easy part

the front is cheap. push front makes a node that points at the old head, and moves the head to it. pop front moves the head to the second node and hands back the first. one arrow changes either way, however long the list is: that's a stack.

everything else starts with a walk. to get item i you start at the head and follow i arrows. a walk of i steps is O(i), and the end of the list is the farthest point.

## the operations

> **interactive figure:** an interactive singly linked list that starts as 4, 8, 15. buttons push and pop at the front, push at the back, reverse, and get, insert and remove at an index you pick. nodes are boxes with arrows, the head box on the left. a walk marks prev or node under each node it passes, an insert shows the new node lifted above the row, pointing at its next node before prev points at it, a remove lifts the node out as the arrow before it skips over, and reverse marks prev, cur and next while each arrow turns around. the matching pseudocode line is highlighted, and a counter shows the nodes walked past.

push to the front a few times: one step each. then insert near the end and watch prev walk the whole way first. reverse shows the three pointers at work.

## try it

> **interactive figure:** a practice exercise. a linked list is drawn as boxes and arrows. some questions ask how many arrows a walk follows: get at an index, or how far prev steps before an insert. others ask what the list looks like after an insert, a remove or a reverse, with a few lists to pick from.

## pseudocode

```text
insert(l, i, x):  # 0 <= i <= l.size
  prev = l.dummy  # a node in front of the head
  repeat i times: prev = prev.next
  prev.next = node(x, next=prev.next)
  l.size += 1

remove(l, i):  # 0 <= i < l.size
  prev = l.dummy
  repeat i times: prev = prev.next
  gone = prev.next
  prev.next = gone.next  # skip over it
  l.size -= 1
  return gone.value

get(l, i):  # 0 <= i < l.size
  node = l.dummy.next
  repeat i times: node = node.next
  return node.value

push_front(l, x): insert(l, 0, x)
pop_front(l): return remove(l, 0)
push_back(l, x): insert(l, l.size, x)  # walks the whole list

reverse(l):
  prev = none
  cur = l.dummy.next
  while cur is not none:
    next = cur.next
    cur.next = prev  # turn the arrow around
    prev = cur
    cur = next
  l.dummy.next = prev
```

`l.dummy` is a node in front of the head that holds no value. index 0 then has a node before it like every other index, so insert and remove never need a special case for the head. the playground draws it as the head box.

## insert, remove and reverse, up close

- **the walk is the cost, the change is free.** an insert at index i walks prev i steps, then makes one new node and moves one arrow. a remove walks the same way and moves one arrow. if you already hold the node before, both are O(1)
- **link the new node before you move prev's arrow.** the new node takes prev's old next first; only then does prev point at it. do it the other way round and you've lost the rest of the list
- **removing without a special case for the head.** the c, go and rust tabs walk a pointer to the link itself: `Node **` in c, `**node[T]` in go, `&mut Option<Box<Node>>` in rust. at index 0 that's the head, further on it's a node's next field, and either way the change is the same line. python and typescript put a dummy node in front of the head, like the pseudocode. swift checks for the head first
- **reverse in one pass, with three pointers.** prev, cur and next. save next before you turn cur's arrow, because turning it overwrites the only way forward. then step prev and cur along. each node's arrow changes once, so it's O(n) with no new nodes
- **no tail pointer here.** a pointer to the last node makes push back O(1), and queues on linked lists keep one. but in rust, a second pointer at a node the `Box`es already own takes `unsafe` or reference counting, so these tabs walk to the end instead

## complexity

| operation                              | cost |
| -------------------------------------- | ---- |
| push front, pop front                  | O(1) |
| get(i), insert at i, remove at i       | O(i) |
| insert or remove after a node you hold | O(1) |
| push back, no tail pointer             | O(n) |
| reverse                                | O(n) |

there's no amortized column: nothing grows or copies, so every operation always costs the same. space is O(n), plus an arrow per node.

> **interactive figure:** a picture of memory. on top, an array: six values side by side in one block, so the next item is always the next slot. below, a linked list: four values placed at scattered addresses in a strip of memory, with arrows hopping back and forth between them in list order.

the big-o table hides one more cost. walking an array reads memory in order, and processors are built for that. walking a list jumps to wherever each node landed. rust's documentation says it outright: array-based containers are almost always the better choice, faster and lighter on memory and the cpu cache.[^rust]

## implementations

each tab is the real file from the repo, checked by its tests (`go test`, `cargo test`, `vitest`, `make test`, `swift test`, `python -m unittest`), including 2000 seeded operations, reverse among them, checked against the language's own list, or a plain array in c. out of range is where they differ: go returns `false`, rust `None`, typescript `undefined`, c returns `false`, swift `nil`, and python raises `IndexError`. the rust and swift lists free their nodes in a loop: by default each node is freed from inside the cleanup of the node before it, and on a long list that much recursion can overflow the stack.

`go/algos/linkedlist/linkedlist.go`

```go
// Package linkedlist is a reference singly linked list: O(1) push and pop at the front, O(i) to
// reach item i. inserting or removing is O(1) once you're at the node before.
package linkedlist

type node[T any] struct {
	value T
	next  *node[T]
}

// List is a singly linked list with no tail pointer. The zero value is an empty list, ready to use.
type List[T any] struct {
	head   *node[T]
	length int
}

// Len returns how many items are in the list.
func (l *List[T]) Len() int {
	return l.length
}

// link returns the pointer that points at node i: &l.head for 0, else the next field of node i - 1.
// inserting and removing rewrite that one pointer, so the head needs no special case.
func (l *List[T]) link(i int) **node[T] {
	link := &l.head
	for range i {
		link = &(*link).next
	}
	return link
}

// Insert puts x at index i. i can be Len() (the end). It returns false outside 0 <= i <= Len().
func (l *List[T]) Insert(i int, x T) bool {
	if i < 0 || i > l.length {
		return false
	}
	link := l.link(i)
	*link = &node[T]{value: x, next: *link}
	l.length++
	return true
}

// Remove takes item i out: the link to it skips over it. It returns false unless 0 <= i < Len().
func (l *List[T]) Remove(i int) (T, bool) {
	if i < 0 || i >= l.length {
		var zero T
		return zero, false
	}
	link := l.link(i)
	gone := *link
	*link = gone.next
	l.length--
	return gone.value, true
}

// PushFront adds x at the front.
func (l *List[T]) PushFront(x T) {
	l.Insert(0, x)
}

// PopFront takes the front item off. It returns false if the list is empty.
func (l *List[T]) PopFront() (T, bool) {
	return l.Remove(0)
}

// PushBack adds x at the end. There's no tail pointer, so it walks the whole list.
func (l *List[T]) PushBack(x T) {
	l.Insert(l.length, x)
}

// Get returns item i, walking i nodes, and false unless 0 <= i < Len().
func (l *List[T]) Get(i int) (T, bool) {
	if i < 0 || i >= l.length {
		var zero T
		return zero, false
	}
	return (*l.link(i)).value, true
}

// Reverse turns every next pointer around: three pointers, one pass, no new nodes.
func (l *List[T]) Reverse() {
	var prev *node[T]
	cur := l.head
	for cur != nil {
		next := cur.next // save it: the next line overwrites it
		cur.next = prev
		prev = cur
		cur = next
	}
	l.head = prev
}

// Values returns the items front to back.
func (l *List[T]) Values() []T {
	out := make([]T, 0, l.length)
	for n := l.head; n != nil; n = n.next {
		out = append(out, n.value)
	}
	return out
}
```

`rust/algos/src/linked_list.rs`

```rust
//! singly linked list: O(1) push and pop at the front, O(i) to reach item i. inserting or removing is O(1) once you're at the node before.

type Link<T> = Option<Box<Node<T>>>;

struct Node<T> {
    value: T,
    next: Link<T>,
}

/// A singly linked list with no tail pointer: holding one next to the `Box`es that own the nodes
/// would take `unsafe` or reference counting, so `push_back` walks to the end.
pub struct LinkedList<T> {
    head: Link<T>,
    len: usize,
}

impl<T> LinkedList<T> {
    /// Makes an empty list.
    pub fn new() -> Self {
        Self { head: None, len: 0 }
    }

    /// The number of items.
    pub fn len(&self) -> usize {
        self.len
    }

    /// Whether there are no items.
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// The link that points at node `i`: the head for 0, else node `i - 1`'s `next`. Inserting and
    /// removing rewrite that one `Option`, so the head needs no special case. `i` must be at most `len`.
    fn link(&mut self, i: usize) -> &mut Link<T> {
        let mut link = &mut self.head;
        for _ in 0..i {
            link = &mut link.as_mut().expect("i is at most len").next;
        }
        link
    }

    /// Puts `x` at index `i`. `i` can be `len` (the end). False if `i > len`.
    pub fn insert(&mut self, i: usize, value: T) -> bool {
        if i > self.len {
            return false;
        }
        let link = self.link(i);
        let next = link.take(); // the new node points where the link pointed
        *link = Some(Box::new(Node { value, next }));
        self.len += 1;
        true
    }

    /// Takes item `i` out: the link to it skips over it. `None` unless `i < len`.
    pub fn remove(&mut self, i: usize) -> Option<T> {
        if i >= self.len {
            return None;
        }
        let link = self.link(i);
        let gone = link.take()?;
        let Node { value, next } = *gone;
        *link = next;
        self.len -= 1;
        Some(value)
    }

    /// Adds `x` at the front.
    pub fn push_front(&mut self, x: T) {
        self.insert(0, x);
    }

    /// Takes the front item off, or `None` if the list is empty.
    pub fn pop_front(&mut self) -> Option<T> {
        self.remove(0)
    }

    /// Adds `x` at the end, walking the whole list to get there.
    pub fn push_back(&mut self, x: T) {
        self.insert(self.len, x);
    }

    /// Item `i`, walking `i` nodes, or `None` unless `i < len`.
    pub fn get(&self, i: usize) -> Option<&T> {
        let mut node = self.head.as_deref();
        for _ in 0..i {
            node = node?.next.as_deref();
        }
        node.map(|n| &n.value)
    }

    /// Turns every `next` around: one pass, no new nodes. `take()` moves each box out so it can be
    /// relinked.
    pub fn reverse(&mut self) {
        let mut prev: Link<T> = None;
        let mut cur = self.head.take();
        while let Some(mut node) = cur {
            cur = node.next.take();
            node.next = prev;
            prev = Some(node);
        }
        self.head = prev;
    }

    /// The values, front to back.
    pub fn iter(&self) -> impl Iterator<Item = &T> {
        std::iter::successors(self.head.as_deref(), |n| n.next.as_deref()).map(|n| &n.value)
    }
}

impl<T> Default for LinkedList<T> {
    fn default() -> Self {
        Self::new()
    }
}

/// The default drop would free the head, whose drop frees the next node, and so on: one stack frame
/// per node, so a long list overflows the stack. This loop frees them one at a time instead.
impl<T> Drop for LinkedList<T> {
    fn drop(&mut self) {
        let mut cur = self.head.take();
        while let Some(mut node) = cur {
            cur = node.next.take();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn from(xs: &[i64]) -> LinkedList<i64> {
        let mut l = LinkedList::new();
        for &x in xs {
            l.push_back(x);
        }
        l
    }

    fn values(l: &LinkedList<i64>) -> Vec<i64> {
        l.iter().copied().collect()
    }

    #[test]
    fn starts_empty() {
        let mut l = LinkedList::<i64>::new();
        assert!(l.is_empty());
        assert_eq!(l.get(0), None);
        assert_eq!((l.pop_front(), l.remove(0)), (None, None));
    }

    #[test]
    fn the_front_is_a_stack() {
        let mut l = LinkedList::new();
        for x in [1, 2, 3] {
            l.push_front(x);
        }
        assert_eq!(
            [l.pop_front(), l.pop_front(), l.pop_front()],
            [Some(3), Some(2), Some(1)]
        );
    }

    #[test]
    fn push_back_and_get() {
        let l = from(&[10, 20, 30]);
        assert_eq!(values(&l), [10, 20, 30]);
        assert_eq!((l.get(0), l.get(2), l.get(3)), (Some(&10), Some(&30), None));
    }

    #[test]
    fn insert_and_remove_front_middle_end() {
        let mut l = from(&[2, 4]);
        assert!(l.insert(0, 1) && l.insert(2, 3) && l.insert(4, 5));
        assert_eq!(values(&l), [1, 2, 3, 4, 5]);
        assert!(!l.insert(7, 9));
        assert_eq!(
            [l.remove(0), l.remove(1), l.remove(2)],
            [Some(1), Some(3), Some(5)]
        );
        assert_eq!(values(&l), [2, 4]);
        assert_eq!(l.remove(2), None);
    }

    #[test]
    fn reverse_twice_is_the_start_again() {
        let mut l = from(&[1, 2, 3, 4]);
        l.reverse();
        assert_eq!(values(&l), [4, 3, 2, 1]);
        l.reverse();
        assert_eq!(values(&l), [1, 2, 3, 4]);
        for xs in [&[][..], &[7]] {
            let mut short = from(xs);
            short.reverse();
            assert_eq!(values(&short), xs);
        }
    }

    #[test]
    fn a_long_list_drops_without_overflowing_the_stack() {
        let mut l = LinkedList::new();
        for x in 0..1_000_000 {
            l.push_front(x);
        }
        drop(l);
    }

    #[test]
    fn agrees_with_vec_over_2000_seeded_ops() {
        let mut state: u32 = 42;
        let mut next = || {
            state ^= state << 13;
            state ^= state >> 17;
            state ^= state << 5;
            state as usize
        };
        let mut l = LinkedList::new();
        let mut model: Vec<i64> = Vec::new();
        for n in 0..2000 {
            let n = n as i64;
            let i = next() % (model.len() + 2);
            match next() % 7 {
                0 => {
                    l.push_front(n);
                    model.insert(0, n);
                }
                1 => {
                    let want = (!model.is_empty()).then(|| model.remove(0));
                    assert_eq!(l.pop_front(), want);
                }
                2 => {
                    l.push_back(n);
                    model.push(n);
                }
                3 => assert_eq!(l.get(i), model.get(i)),
                4 => {
                    let ok = i <= model.len();
                    assert_eq!(l.insert(i, n), ok);
                    if ok {
                        model.insert(i, n);
                    }
                }
                5 => {
                    let want = (i < model.len()).then(|| model.remove(i));
                    assert_eq!(l.remove(i), want);
                }
                _ => {
                    l.reverse();
                    model.reverse();
                }
            }
            assert_eq!(l.len(), model.len());
        }
        assert_eq!(values(&l), model);
    }
}
```

`site/src/visuals/linked-list/linked-list.ts`

```ts
/**
 * Singly linked list: O(1) push and pop at the front, O(i) to reach item i. Inserting or removing is O(1)
 * once you're at the node before, and getting there is the walk.
 */
type Node<T> = { value: T; next: Node<T> | null };

export class LinkedList<T> {
  // a dummy node in front of the head: inserting or removing at index 0 works like anywhere else,
  // since every real node then has a node before it
  #dummy: Node<T | undefined> = { value: undefined, next: null };
  #length = 0;

  get length(): number {
    return this.#length;
  }

  pushFront(x: T): void {
    this.insert(0, x);
  }

  popFront(): T | undefined {
    return this.remove(0);
  }

  /** O(n): there's no tail pointer, so it walks to the last node. */
  pushBack(x: T): void {
    this.insert(this.#length, x);
  }

  get(i: number): T | undefined {
    if (!Number.isInteger(i) || i < 0 || i >= this.#length) return undefined;
    return (this.#before(i).next as Node<T>).value;
  }

  /** Put x at index i. i can be length (the end). */
  insert(i: number, x: T): boolean {
    if (!Number.isInteger(i) || i < 0 || i > this.#length) return false;
    const prev = this.#before(i);
    prev.next = { value: x, next: prev.next as Node<T> | null };
    this.#length += 1;
    return true;
  }

  /** Take item i out: the node before it skips over it. */
  remove(i: number): T | undefined {
    if (!Number.isInteger(i) || i < 0 || i >= this.#length) return undefined;
    const prev = this.#before(i);
    const gone = prev.next as Node<T>;
    prev.next = gone.next;
    this.#length -= 1;
    return gone.value;
  }

  /** Turn every arrow around: three pointers, one pass, no new nodes. */
  reverse(): void {
    let prev: Node<T> | null = null;
    let cur = this.#dummy.next as Node<T> | null;
    while (cur) {
      const next: Node<T> | null = cur.next;
      cur.next = prev;
      prev = cur;
      cur = next;
    }
    this.#dummy.next = prev;
  }

  /** The values front to back. */
  values(): T[] {
    const out: T[] = [];
    for (let n = this.#dummy.next as Node<T> | null; n; n = n.next) out.push(n.value);
    return out;
  }

  /** The node before index i: the dummy for 0, after i steps. */
  #before(i: number): Node<T | undefined> {
    let node = this.#dummy;
    for (let k = 0; k < i; k++) node = node.next as Node<T | undefined>;
    return node;
  }
}
```

`c/algos/linked_list.c`

```c
/* singly linked list: O(1) push and pop at the front, O(i) to reach item i. inserting or removing is O(1) once you're at the node before. */
#include "linked_list.h"

#include <stdlib.h>

void ll_init(LinkedList *l) {
    l->head = NULL;
    l->len = 0;
}

void ll_free(LinkedList *l) {
    Node *n = l->head;
    while (n) {
        Node *next = n->next;
        free(n);
        n = next;
    }
    ll_init(l);
}

/* the link that points at node i: &head for 0, else the next field of node i - 1. inserting and
   removing rewrite that one pointer, so the head needs no special case */
static Node **link_at(LinkedList *l, size_t i) {
    Node **link = &l->head;
    while (i--) link = &(*link)->next;
    return link;
}

bool ll_insert(LinkedList *l, size_t i, int x) {
    if (i > l->len) return false;
    Node *n = malloc(sizeof *n);
    if (!n) return false;
    Node **link = link_at(l, i);
    n->value = x;
    n->next = *link; /* the new node points where the link pointed */
    *link = n;       /* and the link points at the new node */
    l->len++;
    return true;
}

bool ll_remove(LinkedList *l, size_t i, int *out) {
    if (i >= l->len) return false;
    Node **link = link_at(l, i);
    Node *gone = *link;
    *link = gone->next; /* the link skips over the node */
    *out = gone->value;
    free(gone);
    l->len--;
    return true;
}

bool ll_push_front(LinkedList *l, int x) {
    return ll_insert(l, 0, x);
}

bool ll_pop_front(LinkedList *l, int *out) {
    return ll_remove(l, 0, out);
}

bool ll_push_back(LinkedList *l, int x) {
    return ll_insert(l, l->len, x);
}

bool ll_get(const LinkedList *l, size_t i, int *out) {
    if (i >= l->len) return false;
    const Node *n = l->head;
    while (i--) n = n->next;
    *out = n->value;
    return true;
}

void ll_reverse(LinkedList *l) {
    Node *prev = NULL, *cur = l->head;
    while (cur) {
        Node *next = cur->next; /* save it: the next line overwrites it */
        cur->next = prev;
        prev = cur;
        cur = next;
    }
    l->head = prev;
}
```

`swift/algos/LinkedList.swift`

```swift
/// singly linked list: O(1) push and pop at the front, O(i) to reach item i. inserting or removing is O(1) once you're at the node before.
/// a class, since its nodes are shared references: copying a struct around them wouldn't copy the list.
public final class LinkedList<Element> {
    final class Node {
        var value: Element
        var next: Node?

        init(_ value: Element, next: Node?) {
            self.value = value
            self.next = next
        }
    }

    private var head: Node?
    public private(set) var count = 0

    public init() {}

    public func pushFront(_ x: Element) {
        head = Node(x, next: head)
        count += 1
    }

    public func popFront() -> Element? {
        guard let first = head else { return nil }
        head = first.next
        count -= 1
        return first.value
    }

    /// walks to the end: there's no tail pointer
    public func pushBack(_ x: Element) {
        insert(x, at: count)
    }

    public func get(_ i: Int) -> Element? {
        guard 0 <= i, i < count else { return nil }
        return node(at: i).value
    }

    /// puts x at index i. i can be count (the end). the head has no node before it, so it's its own case
    @discardableResult
    public func insert(_ x: Element, at i: Int) -> Bool {
        guard 0 <= i, i <= count else { return false }
        if i == 0 {
            pushFront(x)
            return true
        }
        let prev = node(at: i - 1)
        prev.next = Node(x, next: prev.next)
        count += 1
        return true
    }

    /// takes item i out: the node before it skips over it
    public func remove(at i: Int) -> Element? {
        guard 0 <= i, i < count else { return nil }
        if i == 0 { return popFront() }
        let prev = node(at: i - 1)
        let gone = prev.next!
        prev.next = gone.next
        count -= 1
        return gone.value
    }

    /// turns every next around: three references, one pass, no new nodes
    public func reverse() {
        var prev: Node? = nil
        var cur = head
        while let node = cur {
            cur = node.next // save it: the next line overwrites it
            node.next = prev
            prev = node
        }
        head = prev
    }

    /// the values front to back
    public var values: [Element] {
        var out: [Element] = []
        var cur = head
        while let node = cur {
            out.append(node.value)
            cur = node.next
        }
        return out
    }

    private func node(at i: Int) -> Node {
        var node = head!
        for _ in 0..<i { node = node.next! }
        return node
    }

    // releasing the head would release the next node from inside that release, and so on: one stack
    // frame per node, enough to crash on a long list. unlink them one at a time instead
    deinit {
        var cur = head
        head = nil
        while let node = cur {
            cur = node.next
            node.next = nil
        }
    }
}
```

`python/algos/linked_list.py`

```python
"""singly linked list: O(1) push and pop at the front, O(i) to reach item i. inserting or removing is O(1) once you're at the node before."""

from __future__ import annotations

from typing import Any, Generic, Iterator, TypeVar

T = TypeVar("T")


class _Node:
    __slots__ = ("value", "next")

    def __init__(self, value: Any, next: _Node | None = None) -> None:
        self.value = value
        self.next = next


class LinkedList(Generic[T]):
    """A singly linked list with no tail pointer, so push_back walks to the end."""

    def __init__(self) -> None:
        # a dummy node in front of the head: index 0 has a node before it like every other index,
        # so insert and remove need no special case for the head
        self._dummy = _Node(None)
        self._length = 0

    def __len__(self) -> int:
        return self._length

    def __iter__(self) -> Iterator[T]:
        node = self._dummy.next
        while node is not None:
            yield node.value
            node = node.next

    def push_front(self, x: T) -> None:
        self.insert(0, x)

    def pop_front(self) -> T:
        if self._length == 0:
            raise IndexError("pop from an empty list")
        return self.remove(0)

    def push_back(self, x: T) -> None:
        self.insert(self._length, x)

    def get(self, i: int) -> T:
        """Return item i, walking i nodes. Raises IndexError outside 0 <= i < len."""
        self._check(i)
        return self._before(i).next.value

    def insert(self, i: int, x: T) -> None:
        """Put x at index i. i can be len (the end)."""
        if not 0 <= i <= self._length:
            raise IndexError("list index out of range")
        prev = self._before(i)
        prev.next = _Node(x, prev.next)
        self._length += 1

    def remove(self, i: int) -> T:
        """Take item i out: the node before it skips over it."""
        self._check(i)
        prev = self._before(i)
        gone = prev.next
        prev.next = gone.next
        self._length -= 1
        return gone.value

    def reverse(self) -> None:
        """Turn every arrow around: three pointers, one pass, no new nodes."""
        prev = None
        cur = self._dummy.next
        while cur is not None:
            nxt = cur.next  # save it: the next line overwrites it
            cur.next = prev
            prev = cur
            cur = nxt
        self._dummy.next = prev

    def _check(self, i: int) -> None:
        if not 0 <= i < self._length:
            raise IndexError("list index out of range")

    def _before(self, i: int) -> _Node:
        """The node before index i: the dummy for 0."""
        node = self._dummy
        for _ in range(i):
            node = node.next
        return node
```

## pitfalls

- **losing the rest of the list.** overwrite an arrow before you've saved where it pointed, and everything after it is unreachable: in c that's a leak, elsewhere garbage. save next first
- **forgetting the head.** inserting or removing at index 0 changes the head, not a node's next. a dummy node or a pointer to the link handles it in one code path
- **walking off the end.** check for the end before following an arrow. an index past the end is a null arrow followed
- **using it where an array would do.** if you mostly read by index or loop over everything, a [dynamic array](/ds/dynamic-array/) is faster: no walk, and memory in order[^rust]
- **recursion on long lists.** anything that recurses once per node, a recursive free or a recursive print, can run out of stack on a long list. loop instead

## variants

- **doubly linked.** each node also points back, so removing a node you hold is O(1) without the node before it, and you can walk either way. java's `LinkedList` is one, and its index lookups walk from whichever end is closer[^java]
- **circular, with a sentinel.** the last node points back at a sentinel node that's also in front of the first, so the list is never empty and the ends need no checks. go's `container/list` is a doubly linked ring around a sentinel `root`[^go]
- **intrusive.** the arrows live inside your own structs instead of nodes that wrap them, so one struct can sit in several lists. the linux kernel's `list_head` works this way, and `list_entry` gets from the arrows back to the struct around them[^linux]
- **unrolled.** each node holds a small array of items, not one, so walks touch fewer nodes. cpython's `deque` is a doubly linked list of 64-item blocks[^cpython]

## practice

- [reverse linked list](https://leetcode.com/problems/reverse-linked-list/): the three-pointer loop
- [merge two sorted lists](https://leetcode.com/problems/merge-two-sorted-lists/): a dummy head makes it clean
- [remove nth node from end of list](https://leetcode.com/problems/remove-nth-node-from-end-of-list/): two pointers, n apart
- [linked list cycle](https://leetcode.com/problems/linked-list-cycle/): a slow and a fast pointer
- [lru cache](https://leetcode.com/problems/lru-cache/): a hash table pointing into a doubly linked list

## how real libraries do it

- **go.** `container/list` is a doubly linked list, kept as a ring around a sentinel element[^go]
- **java.** `LinkedList` is doubly linked, and implements both `List` and `Deque`[^java]
- **rust.** `LinkedList` is doubly linked with owned nodes, and its docs point you to `Vec` or `VecDeque` for almost everything[^rust]
- **python.** no linked list type. `collections.deque` is a linked list of blocks under the hood[^cpython]
- **c.** none in the standard library. the linux kernel's intrusive `list_head` is the best-known one[^linux]

[^rust]: [LinkedList](https://doc.rust-lang.org/std/collections/struct.LinkedList.html) in the rust docs: a doubly-linked list with owned nodes, and a note that it's almost always better to use `Vec` or `VecDeque`, since array-based containers are generally faster, more memory efficient, and make better use of the cpu cache.

[^java]: [LinkedList](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/LinkedList.html) in the java 21 docs: a doubly-linked implementation of `List` and `Deque`, whose index operations traverse from the beginning or the end, whichever is closer.

[^go]: [list.go](https://github.com/golang/go/blob/go1.27.2/src/container/list/list.go#L14-L20) at go1.27.2: a doubly linked list implemented as a ring, where the list's sentinel `root` is both after the last element and before the first.

[^linux]: [list.h](https://github.com/torvalds/linux/blob/v7.2/include/linux/list.h#L12-L20) in linux v7.2, "circular doubly linked list implementation", with [`struct list_head`](https://github.com/torvalds/linux/blob/v7.2/include/linux/types.h#L204-L206) holding just the two pointers, and `list_entry` built on `container_of` to get back to the struct around them.

[^cpython]: [`_collectionsmodule.c`](https://github.com/python/cpython/blob/v3.15.0/Modules/_collectionsmodule.c#L71-L98) in cpython 3.15.0: the deque is a doubly linked list of 64-slot blocks.

## related

- https://learning.anthnydas.com/ds/dynamic-array.md
- https://learning.anthnydas.com/ds/stack-queue.md
- https://learning.anthnydas.com/ds/hash-table.md
- https://learning.anthnydas.com/ds/graph.md
