Linked lists · prepend/append O(1); find/remove O(n)

Singly linked list

Prepend, append, find, remove and in-place reversal with stable node identities.

The full explanation, derivation and practice are in the lesson Singly linked lists: nodes, head and tail.

Implementation

The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.

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