Programming

Linked lists in C++: ownership before menu options

A linked list is a good ownership exercise, but a long menu does not make its pointer handling correct.

Four small linked memory blocks with clear pointer arrows and one detached block in a soft outline

A linked list is a good ownership exercise, but a long menu does not make its pointer handling correct. The old example dereferenced an uninitialized head pointer and mixed data storage, file output and screen controls in the same class.

Start with a container that owns its nodes#

For ordinary application code, a standard container is a clearer baseline:

cpp
#include <forward_list>
#include <iostream>

int main()
{
    std::forward_list<int> values{3, 1, 2};
    values.sort();
    values.remove(2);
    values.push_front(0);
    for (int value : values) {
        std::cout << value << ' ';
    }
    std::cout << '\n';
}

The expected sequence is 0 1 3. The container releases its nodes when it goes out of scope. See the `forward_list` reference for its iterator and insertion rules.

If you build your own list#

Define what an empty list means before implementing insertion. Decide who owns each allocated node, how copying works, and what happens when allocation or input fails. Test an empty list, a single node and removal at both ends before adding sorting or file persistence.

Add a menu or a storage format only after the underlying container behaves correctly. Keeping those concerns separate makes failures much easier to locate.