C++ · Module 18 · Lesson 21 min read

A Templated Linked List Class

Node structure

arduino
template <typename T>
class LinkedList {
    struct Node {
        T value;
        std::unique_ptr<Node> next;   // each node OWNS the next one
    };
    std::unique_ptr<Node> head_;
    Node* tail_ = nullptr;            // non-owning shortcut for O(1) push_back
    std::size_t size_ = 0;
};

unique_ptr makes memory management automatic: destroying the head destroys the whole chain.

⚠️ Recursive destruction

A chain of 1,000,000 unique_ptrs would destroy recursively and may overflow the stack. Write a destructor that releases nodes in a loop.

Operations

OperationComplexity
push_frontO(1)
push_back (with tail pointer)O(1)
pop_frontO(1)
find(value)O(n)
remove(value)O(n)
reverse()O(n), O(1) extra space
access by indexO(n)

Making it work with range-for

Provide an iterator class with operator*, operator++, operator!= (and operator==), plus begin()/end() in the list. Then for (auto& x : list) and many STL algorithms work.

Reversing in place

Walk the list with prev, curr, next, flipping each link. With unique_ptr, use std::move to transfer ownership of each link.

Copying

Implement a copy constructor that copies node by node (deep copy) — or delete copying and allow only moves.

In real code

Use std::list or std::forward_list; this lesson is about understanding them.

Example

C++
#include <iostream>
#include <memory>
#include <string>

template <typename T>
class LinkedList {
    struct Node {
        T value;
        std::unique_ptr<Node> next;
    };
public:
    class Iterator {
    public:
        explicit Iterator(Node* n) : node_(n) {}
        T& operator*() const { return node_->value; }
        Iterator& operator++() { node_ = node_->next.get(); return *this; }
        bool operator==(const Iterator& o) const { return node_ == o.node_; }
    private:
        Node* node_;
    };

    LinkedList() = default;
    LinkedList(std::initializer_list<T> init) { for (const T& x : init) push_back(x); }
    ~LinkedList() { while (head_) head_ = std::move(head_->next); }   // iterative: no deep recursion
    LinkedList(const LinkedList&) = delete;
    LinkedList& operator=(const LinkedList&) = delete;

    void push_front(T value) {
        head_ = std::make_unique<Node>(Node{ std::move(value), std::move(head_) });
        if (!tail_) tail_ = head_.get();
        ++size_;
    }
    void push_back(T value) {
        auto node = std::make_unique<Node>(Node{ std::move(value), nullptr });
        Node* raw = node.get();
        if (tail_) tail_->next = std::move(node); else head_ = std::move(node);
        tail_ = raw;
        ++size_;
    }
    bool remove(const T& value) {
        for (std::unique_ptr<Node>* link = &head_; *link; link = &(*link)->next) {
            if ((*link)->value == value) {
                *link = std::move((*link)->next);
                --size_;
                fix_tail();
                return true;
            }
        }
        return false;
    }
    void reverse() {
        std::unique_ptr<Node> prev;
        tail_ = head_.get();
        while (head_) {
            auto next = std::move(head_->next);
            head_->next = std::move(prev);
            prev = std::move(head_);
            head_ = std::move(next);
        }
        head_ = std::move(prev);
    }
    std::size_t size() const { return size_; }
    Iterator begin() { return Iterator(head_.get()); }
    Iterator end() { return Iterator(nullptr); }

private:
    void fix_tail() {
        tail_ = nullptr;
        for (Node* n = head_.get(); n; n = n->next.get()) tail_ = n;
    }
    std::unique_ptr<Node> head_;
    Node* tail_ = nullptr;
    std::size_t size_ = 0;
};

template <typename T>
void print(LinkedList<T>& list, const char* label) {
    std::cout << label << " (" << list.size() << "):";
    for (const auto& x : list) std::cout << ' ' << x;
    std::cout << '\n';
}

int main() {
    LinkedList<int> nums = { 2, 3, 4 };
    nums.push_front(1);
    nums.push_back(5);
    print(nums, "list");
    nums.remove(3);
    nums.remove(5);
    nums.push_back(6);                       // tail was fixed after removing the last node
    print(nums, "after removes");
    nums.reverse();
    print(nums, "reversed");
    for (auto& x : nums) x *= 10;            // iterator gives references
    print(nums, "times 10");

    LinkedList<std::string> tasks;
    tasks.push_back("pay rent");
    tasks.push_back("buy groceries");
    tasks.push_front("check balance");
    print(tasks, "tasks");

    LinkedList<int> big;
    for (int i = 0; i < 200'000; ++i) big.push_front(i);
    std::cout << "built and destroyed a list of " << big.size() << " nodes safely\n";
    return 0;
}

/* Output:
list (5): 1 2 3 4 5
after removes (4): 1 2 4 6
reversed (4): 6 4 2 1
times 10 (4): 60 40 20 10
tasks (3): check balance pay rent buy groceries
built and destroyed a list of 200000 nodes safely
*/