M07 · Linked Lists

Singly Linked Lists: Nodes, Head and Tail

A linked list stores each element in its own node and chains the nodes together with references. Adding at the front costs the same whether the list has three nodes or three million, but finding anything means walking from the head. This lesson traces every pointer write and shows what the built-in linked lists really offer.

~35 minBeginnerC# · Python · Java · C++
Curriculum: M07 Linked Lists · 1 of 1 lessons available

You will be able to

  • Draw a singly linked list as nodes, next pointers, head and tail, and say which references each operation changes.
  • Explain why prepend is O(1), why append is O(1) only with a tail reference, and why removing the last node is still O(n).
  • Remove a node by value using a previous pointer, keeping head, tail and size correct in every case.
  • Reverse a list in place with three pointers and argue that it is Θ(n) time and O(1) extra space.
  • Compare linked lists with dynamic arrays and choose the built-in list type in C#, Python, Java or C++ that fits a task.

Helpful before this lesson

  • M02 Memory Model — What a variable, a reference and a buffer really are, and why contiguous memory is fast.
  • M03 Big O — Count operations, describe growth, and tell worst-case, average and amortized costs apart.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Mental model

An array keeps its elements side by side, so it can compute where element i lives. A linked list gives that up. Every element sits in its own small object, a node, which holds the value and a reference to the next node. The nodes can be anywhere in memory; the only thing that holds them together is the chain of next references.

The list object itself stores very little:

  • head: the first node, or null when the list is empty.
  • tail: the last node, or null when the list is empty. Optional, but it changes what append costs.
  • count: the number of nodes, so asking for the size does not need a walk.

The last node's next is null, which is how a walk knows it has reached the end. In the lab, each box is a node and each arrow is a next pointer. Watch the Reverse in place preset: the boxes do not move, only the arrows do. That is the whole idea of a linked structure. Changing the shape means rewriting a few references, not copying elements.

The operations, pointer by pointer

Prepend

node = new Node(value)
node.next = head
head = node
if tail is null: tail = node     # the list was empty
count += 1

Two or three pointer writes, no matter how long the list is: O(1). The order matters. If you set head = node first, the old head is no longer reachable and you cannot link to it.

Append

node = new Node(value)
if tail is null: head = tail = node
else:
    tail.next = node
    tail = node
count += 1

Also O(1), but only because the list keeps tail. Without it, append has to walk from the head to find the last node, which is O(n). Many hand-written lists in interview answers forget this.

Find

There is no index arithmetic. To reach position i you follow next exactly i times, so a search by value or a lookup by index is O(n) in the worst case. The teaching index_of returns the position of the first match, or -1 when the walk falls off the end.

Remove by value

To unlink a node you must change the next of the node before it. A singly linked list has no backward pointer, so the walk carries two references: previous and current.

previous = null, current = head
while current is not null and current.value != value:
    previous, current = current, current.next
if current is null: return false            # not found
if previous is null: head = current.next    # removing the head
else:                previous.next = current.next
if tail == current:  tail = previous        # removing the tail
count -= 1
return true

Three cases need care, and the lab's Remove from the middle preset shows all of them: the match is the head (previous is null), the match is the tail (tail must move back), and the value is not present. Forgetting the tail case leaves tail pointing at a detached node, and the next append silently disappears into it.

Once unlinked, nothing refers to the node. C#, Java and Python reclaim it with the garbage collector. The C++ version owns each node through a std::unique_ptr, so overwriting the owning link frees the node at that moment.

Reverse in place

previous = null, current = head
tail = head
while current is not null:
    following = current.next     # save it before it is overwritten
    current.next = previous      # flip one arrow
    previous = current
    current = following
head = previous

Each node is visited once and its arrow flipped once: Θ(n) time, O(1) extra space. The step that saves following is the one people drop. Without it, flipping current.next cuts the list in two and the rest is lost.

Costs and assumptions

Operation Time Notes
prepend O(1) Two pointer writes, three on an empty list.
append O(1) Needs the tail reference; O(n) without it.
read the first or last value O(1) Through head or tail.
find by value, get by index O(n) Walks from the head.
remove by value O(n) The walk dominates; the unlink itself is O(1).
remove the head O(1) head = head.next.
remove the tail O(n) You need the node before the tail, and only a walk finds it.
insert or remove after a node you already hold O(1) This is the real advantage of linked lists.
reverse Θ(n) O(1) extra space.

"Linked lists have O(1) insertion" is only true at a position you already have a reference to. Inserting at index 500 still costs 500 steps to get there. If you mostly look things up by index, a dynamic array is better on every count.

Memory and speed. Each node carries at least one extra reference, and in C#, Java and Python it is a separate heap object with its own header. A list of a million small integers can easily take several times the memory of an array of the same values. The nodes are also scattered, so walking them gets little help from the CPU cache. In practice, a dynamic array often beats a linked list even for workloads that look list-friendly on paper. Measure before choosing.

Invariants the implementation keeps

After every public operation:

  1. head is null exactly when tail is null, exactly when count is 0.
  2. Following next from head reaches tail after count - 1 steps, and tail.next is null.
  3. No node is reachable twice (no cycle).

The shared fixture checks these indirectly: reverse-then-append fails if reverse forgets to move tail, and remove-tail-then-append fails if remove forgets the tail case.

Built-in linked lists

C# Python Java C++
Type LinkedList<T> (doubly linked) no linked list type; collections.deque for the ends LinkedList<E> (doubly linked) std::forward_list<T> (singly), std::list<T> (doubly)
Add at the front / back AddFirst, AddLast appendleft, append addFirst, addLast push_front; std::list also has push_back
Insert next to a known node AddAfter(node, x), AddBefore n/a ListIterator.add insert_after(it, x) / insert(it, x)
Remove a known node Remove(node), O(1) n/a ListIterator.remove, O(1) erase_after(it) / erase(it)
Remove by value Remove(x), O(n) remove(x), O(n) remove(Object), O(n) remove(x) removes all equal elements
Index access none d[i], O(n) in the middle get(i), walks from the nearer end none

Details that matter:

  • C# exposes the nodes themselves (LinkedListNode<T> with Next, Previous, Value). Keep a node and later insertions or removals around it are O(1). Find(x) returns the first matching node.
  • Python has no linked list in the standard library. A list is a dynamic array. deque gives O(1) appends and pops at both ends; the docs describe indexed access as O(1) at the ends and O(n) in the middle. In CPython it is built from linked fixed-size blocks, an implementation detail. If you write your own node class, __slots__ (as the teaching version does) saves memory per node.
  • Java's LinkedList implements both List and Deque. Its get(i) traverses from the head or the tail, whichever is closer, so a loop for (i…) list.get(i) is O(n²). Iterate with a for-each loop or an iterator instead. For queue and stack use, the Javadoc of ArrayDeque says it is likely faster.
  • C++ std::forward_list is the true singly linked list: no size() member, no push_back, and insertion and removal happen after an iterator (before_begin() gives a position before the first element). std::list is doubly linked, has O(1) size() since C++11, and splice moves nodes from one list to another without copying elements. In both, inserting never invalidates other iterators, and erasing invalidates only iterators to the erased element.

The teaching implementation

The four listings are one design: head, tail, count, prepend, append, index_of, remove (first occurrence, returns whether something was removed) and reverse. Equality uses the language's standard comparison: EqualityComparer<T>.Default in C#, Objects.equals in Java, == in Python and C++. The lab's text view shows remove returning the removed value so the trace is easier to follow; the code returns a boolean.

The C++ version shows two ownership details. Nodes own their successor through std::unique_ptr while tail is a plain, non-owning pointer. And the destructor unlinks nodes in a loop: the default destructor would destroy next, which destroys its next, and so on, one stack frame per node, which overflows the stack on a long list.

Common mistakes

  • Losing the rest of the list by overwriting next before saving it (reverse) or by moving head before linking the new node (prepend).
  • Forgetting the empty case. Prepend and append on an empty list must set both head and tail.
  • Forgetting the tail on removal when the removed node was the last one.
  • Dereferencing null. Every walk must check current before reading current.next or current.value.
  • Calling a list "O(1) insert" without a node in hand. Locating the position is the expensive part.
  • Indexing a linked list in a loop, which turns a linear algorithm quadratic.

Edge cases

  • Empty list: find returns -1 without visiting anything; reverse does nothing.
  • One node: it is both head and tail; removing it must make both null.
  • Duplicates: remove and index_of act on the first match only (fixture duplicates).
  • Value not present: the walk reaches null and reports it; nothing changes.
  • Reverse, then append: the old head is the new tail, so the appended node goes after it.

Worked practice

1. Starting empty: append 1, append 2, prepend 0, reverse. What is the list, and which node is the tail?

Answer

Before the reverse the list is 0 → 1 → 2. Reversing gives 2 → 1 → 0, so head is 2 and tail is the node holding 0, the old head.

2. Why is removing the last node O(n) even though the list keeps a tail reference?

Answer

Removing the tail means setting the second-to-last node's next to null and making it the new tail. A singly linked node does not know its predecessor, so the only way to find that node is to walk from the head. A doubly linked list stores prev and can do it in O(1).

3. Suppose reverse forgot the line tail = head. What does append 1, append 2, reverse, append 3 produce?

Answer

After the reverse, tail still refers to node 2, which is now the head. append 3 sets node2.next = node3, which drops the link to node 1. The list becomes 2 → 3 and node 1 is lost (and count says 3). That is exactly the bug the fixture case reverse-then-append catches.

4. How can you find the middle node in one pass without knowing the length?

Answer

Walk two pointers from the head: slow moves one node per step, fast moves two. When fast reaches the end, slow is in the middle. The same fast/slow idea detects a cycle: if the list loops, the fast pointer eventually lands on the slow one.

Summary

  • A linked list is nodes plus next references; head, tail and count live in the list object.
  • Prepend is O(1); append is O(1) with a tail; find, get by index and removing the tail are O(n).
  • Removal needs the previous node; reversal needs a saved next. Both are about not losing references.
  • Insertion and removal are O(1) only at a node you already hold.
  • Arrays usually win on memory and speed; reach for a linked list when you splice, or insert and remove next to nodes you keep references to.

Full implementation

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

References