Data structure · Linear structures
Linked list
Nodes that point to the next node: constant-time insertion at a known position, but no indexing and poor cache locality.
The derivations, edge cases and exercises are in the lesson Contiguous storage, addresses and cache locality. Open it full width in the playground.
On this page
The idea
Each node stores a value and a reference to the next node; the list itself keeps a reference to the head (and here also the tail). Adding or removing a node only rewires a few references, so nothing shifts.
The price is access: reaching the k-th element means following k links, and the nodes are scattered across the heap, so a traversal is slower than an array scan even at the same Big O.
Representation. Separately allocated nodes { value, next }, plus head and tail references and a count.
Operations
| Operation | Time | Extra space | Notes |
|---|---|---|---|
| Prepend | O(1) | O(1) | |
| Append (with a tail reference) | O(1) | O(1) | O(n) without a tail reference. |
| Find by value | O(n) | O(1) | |
| Remove by value | O(n) | O(1) | The search dominates; the unlink itself is O(1). |
| Access by index | O(n) | O(1) | |
| Reverse in place | O(n) | O(1) |
Invariants
What stays true before and after every operation.
- Following next from head visits exactly count nodes and ends at null.
- tail is the last node reached (and null exactly when head is null).
- No node is reachable twice: the list has no cycle.
When to use it
Use it when
- You splice, insert or remove at positions you already hold a reference to, and never need random access.
- You need stable node identities: other code may keep a node while the list changes around it.
Avoid it when
- You index by position or scan often: a dynamic array is faster and smaller.
- Elements are small: the per-node pointer and allocation overhead can exceed the data.
Built-in equivalents
What the standard library of each language offers. Linked types have a full page in the collections encyclopedia with every operation’s complexity, memory effects and a tested example.
C#
LinkedList<T> is doubly linked; LinkedListNode<T> lets you insert or remove at a known node in O(1).
Python
No linked list in the standard library; collections.deque covers the usual queue use cases.
Java
java.util.LinkedList is doubly linked and also implements Deque.
C++
std::forward_list is singly linked; std::list is doubly linked.
Step through it
The interactive lab for linked list: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.
Implementation in four languages
The singly linked list in four languages, checked against one shared fixture of prepend, append, find, remove and reverse sequences.
namespace Bekadan.Dsa.Examples.LinkedLists;
/// <summary>
/// A singly linked list with head and tail references: O(1) prepend and append,
/// O(n) search and removal by value, in-place O(n) reversal.
/// </summary>
public sealed class SinglyLinkedList<T>
{
private sealed class Node(T value)
{
public T Value = value;
public Node? Next;
}
private Node? _head;
private Node? _tail;
public int Count { get; private set; }
public IEnumerable<T> Items()
{
for (var node = _head; node is not null; node = node.Next)
yield return node.Value;
}
public void Prepend(T value)
{
var node = new Node(value);
node.Next = _head;
_head = node;
_tail ??= node;
Count++;
}
public void Append(T value)
{
var node = new Node(value);
if (_tail is null)
_head = _tail = node;
else
_tail = _tail.Next = node;
Count++;
}
public int IndexOf(T value)
{
int index = 0;
for (var node = _head; node is not null; node = node.Next, index++)
{
if (EqualityComparer<T>.Default.Equals(node.Value, value))
return index;
}
return -1;
}
public bool Remove(T value)
{
Node? previous = null;
for (var node = _head; node is not null; previous = node, node = node.Next)
{
if (!EqualityComparer<T>.Default.Equals(node.Value, value))
continue;
if (previous is null)
_head = node.Next;
else
previous.Next = node.Next;
if (_tail == node)
_tail = previous;
Count--;
return true;
}
return false;
}
public void Reverse()
{
Node? previous = null;
var current = _head;
_tail = _head;
while (current is not null)
{
var next = current.Next;
current.Next = previous;
previous = current;
current = next;
}
_head = previous;
}
}
Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/LinkedLists/SinglyLinkedList.cs
"""A singly linked list with head and tail references."""
from collections.abc import Iterator
from typing import Generic, TypeVar
T = TypeVar("T")
class _Node(Generic[T]):
__slots__ = ("value", "next")
def __init__(self, value: T) -> None:
self.value = value
self.next: _Node[T] | None = None
class SinglyLinkedList(Generic[T]):
"""O(1) prepend and append, O(n) search and removal by value, in-place O(n) reversal."""
def __init__(self) -> None:
self._head: _Node[T] | None = None
self._tail: _Node[T] | None = None
self._count = 0
def __len__(self) -> int:
return self._count
def __iter__(self) -> Iterator[T]:
node = self._head
while node is not None:
yield node.value
node = node.next
def prepend(self, value: T) -> None:
node = _Node(value)
node.next = self._head
self._head = node
if self._tail is None:
self._tail = node
self._count += 1
def append(self, value: T) -> None:
node = _Node(value)
if self._tail is None:
self._head = self._tail = node
else:
self._tail.next = node
self._tail = node
self._count += 1
def index_of(self, value: T) -> int:
node, index = self._head, 0
while node is not None:
if node.value == value:
return index
node, index = node.next, index + 1
return -1
def remove(self, value: T) -> bool:
previous, node = None, self._head
while node is not None:
if node.value != value:
previous, node = node, node.next
continue
if previous is None:
self._head = node.next
else:
previous.next = node.next
if self._tail is node:
self._tail = previous
self._count -= 1
return True
return False
def reverse(self) -> None:
previous, current = None, self._head
self._tail = self._head
while current is not None:
following = current.next
current.next = previous
previous, current = current, following
self._head = previous
Tested on CPython 3.14.0 · examples/python/dsa_examples/linked_list.py
package dev.bekadan.dsa.lists;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/** A singly linked list with head and tail references. */
public final class SinglyLinkedList<T> {
private static final class Node<T> {
T value;
Node<T> next;
Node(T value) {
this.value = value;
}
}
private Node<T> head;
private Node<T> tail;
private int count;
public int size() {
return count;
}
public List<T> items() {
List<T> result = new ArrayList<>();
for (Node<T> node = head; node != null; node = node.next) {
result.add(node.value);
}
return result;
}
public void prepend(T value) {
Node<T> node = new Node<>(value);
node.next = head;
head = node;
if (tail == null) {
tail = node;
}
count++;
}
public void append(T value) {
Node<T> node = new Node<>(value);
if (tail == null) {
head = tail = node;
} else {
tail.next = node;
tail = node;
}
count++;
}
public int indexOf(T value) {
int index = 0;
for (Node<T> node = head; node != null; node = node.next, index++) {
if (Objects.equals(node.value, value)) {
return index;
}
}
return -1;
}
public boolean remove(T value) {
Node<T> previous = null;
for (Node<T> node = head; node != null; previous = node, node = node.next) {
if (!Objects.equals(node.value, value)) {
continue;
}
if (previous == null) {
head = node.next;
} else {
previous.next = node.next;
}
if (tail == node) {
tail = previous;
}
count--;
return true;
}
return false;
}
public void reverse() {
Node<T> previous = null;
Node<T> current = head;
tail = head;
while (current != null) {
Node<T> next = current.next;
current.next = previous;
previous = current;
current = next;
}
head = previous;
}
}
Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/lists/SinglyLinkedList.java
#pragma once
#include <cstddef>
#include <memory>
#include <utility>
#include <vector>
namespace bekadan::dsa {
// A singly linked list with head and tail. Nodes are owned through
// std::unique_ptr `next` links (RAII: removing a node frees it); `tail` is a
// non-owning pointer. O(1) prepend and append, O(n) search and removal.
template <typename T>
class SinglyLinkedList {
struct Node {
T value;
std::unique_ptr<Node> next;
explicit Node(T v) : value(std::move(v)) {}
};
public:
SinglyLinkedList() = default;
SinglyLinkedList(const SinglyLinkedList&) = delete;
SinglyLinkedList& operator=(const SinglyLinkedList&) = delete;
~SinglyLinkedList() {
// Unlink iteratively so a long list cannot overflow the stack with recursive destructors.
while (head_) head_ = std::move(head_->next);
}
[[nodiscard]] std::size_t size() const noexcept { return count_; }
[[nodiscard]] std::vector<T> items() const {
std::vector<T> result;
for (Node* node = head_.get(); node; node = node->next.get()) result.push_back(node->value);
return result;
}
void prepend(T value) {
auto node = std::make_unique<Node>(std::move(value));
node->next = std::move(head_);
head_ = std::move(node);
if (!tail_) tail_ = head_.get();
++count_;
}
void append(T value) {
auto node = std::make_unique<Node>(std::move(value));
Node* raw = node.get();
if (!tail_)
head_ = std::move(node);
else
tail_->next = std::move(node);
tail_ = raw;
++count_;
}
[[nodiscard]] std::ptrdiff_t index_of(const T& value) const {
std::ptrdiff_t index = 0;
for (Node* node = head_.get(); node; node = node->next.get(), ++index) {
if (node->value == value)
return index;
}
return -1;
}
bool remove(const T& value) {
Node* previous = nullptr;
for (Node* node = head_.get(); node; previous = node, node = node->next.get()) {
if (!(node->value == value))
continue;
if (tail_ == node) tail_ = previous;
std::unique_ptr<Node>& link = previous ? previous->next : head_;
link = std::move(node->next); // the old owner of `node` is replaced: node is freed here
--count_;
return true;
}
return false;
}
void reverse() {
std::unique_ptr<Node> previous;
std::unique_ptr<Node> current = std::move(head_);
tail_ = current.get();
while (current) {
std::unique_ptr<Node> next = std::move(current->next);
current->next = std::move(previous);
previous = std::move(current);
current = std::move(next);
}
head_ = std::move(previous);
}
private:
std::unique_ptr<Node> head_;
Node* tail_ = nullptr;
std::size_t count_ = 0;
};
} // namespace bekadan::dsa
Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/singly_linked_list.hpp
Learn more
Lessons
- Contiguous storage, addresses and cache locality· M02 Memory Model
- Singly linked lists: nodes, head and tail· M07 Linked Lists
Comparisons
- Dynamic array vs linked list· One operation sequence on a doubling dynamic array and on a singly linked list with a tail reference. Different kinds of work, each counted exactly.
Problems, patterns and exercises
- Complexity exerciseInserting at the front of an array list, n times· Θ(n²)