A singly linked list

Nodes scattered across the heap, held together by one pointer each. Insert, delete and reverse are all a matter of rewiring.

What you'll learn
  • Build a linked list from nodes and next pointers
  • Insert at the front in O(1) and at the back in O(n)
  • Delete a node and reverse the list in place without leaking memory

An array keeps its elements side by side, so element \(i\) is found by arithmetic. A linked list gives that up: each element lives in its own node anywhere on the heap, and carries a pointer to the next one. Finding element \(i\) now means following \(i\) pointers — but inserting or removing a node never moves the others.

The repository’s 01_singly_linked_list.cpp is still an empty file. The implementation below is written for this lesson to fill it; it was compiled and run with AddressSanitizer and UndefinedBehaviorSanitizer, which report no leaks or invalid accesses.

struct Node {
    int value;
    Node *next;
};

class SinglyLinkedList {
public:
    SinglyLinkedList() = default;
    SinglyLinkedList(const SinglyLinkedList &) = delete;             // see below
    SinglyLinkedList &operator=(const SinglyLinkedList &) = delete;

    ~SinglyLinkedList() {
        while (head) {
            Node *dead = head;
            head = head->next;
            delete dead;
        }
    }

    void push_front(int v) { head = new Node{v, head}; }

    void push_back(int v) {
        Node **link = &head;                 // the pointer that must change
        while (*link) link = &(*link)->next;
        *link = new Node{v, nullptr};
    }

    bool remove(int v) {
        for (Node **link = &head; *link; link = &(*link)->next) {
            if ((*link)->value == v) {
                Node *dead = *link;
                *link = dead->next;          // unlink, then free
                delete dead;
                return true;
            }
        }
        return false;
    }

    void reverse() {
        Node *prev = nullptr, *cur = head;
        while (cur) {
            Node *next = cur->next;          // remember the rest
            cur->next = prev;                // flip one arrow
            prev = cur;
            cur = next;
        }
        head = prev;
    }

private:
    Node *head = nullptr;
};
push_back(2), push_back(3), push_front(1), push_back(4), remove(3), then reverse() — the main() below, one pointer change per step. During the reverse, prev, cur and next walk along while each arrow is flipped (green).
int main() {
    SinglyLinkedList list;
    list.push_back(2);
    list.push_back(3);
    list.push_front(1);
    list.push_back(4);   // 1 -> 2 -> 3 -> 4 -> null
    list.remove(3);      // 1 -> 2 -> 4 -> null
    list.reverse();      // 4 -> 2 -> 1 -> null
}

The pointer-to-pointer trick

push_back and remove both walk with Node **link — a pointer to the pointer that will change. At the start it points at head; later at some node’s next. That removes the usual special case for an empty list or for deleting the first node: there is always exactly one pointer to rewrite, and link points at it.

Ownership

The list owns its nodes, so its destructor must free them all. That creates a trap: the compiler-generated copy constructor would copy only head, leaving two lists that both delete the same nodes — a double free. Deleting the copy operations makes the mistake a compile error. (A production list would implement a deep copy instead, or hold its nodes in std::unique_ptr.)

Operation Cost Why
push_front O(1) one new node, one pointer
push_back O(n) walks to the tail (O(1) if a tail pointer is kept)
remove(v) O(n) must find the node first
reverse O(n) one pass, no extra memory

Try it yourself. Add a Node *tail member so push_back becomes O(1). Which other operations must now update it? Then remove the two = delete lines, copy a list with SinglyLinkedList b = list;, and run under -fsanitize=address to see the double free reported.

View source on GitHub →