Construct a singly linked list by allocating one node per value and chaining next references. Establishes the node + head + tail model used by every later linked-list lesson.

Algorithm

Canonical input [10, 20, 30, 40] builds the chain head -> 10 -> 20 -> 30 -> 40 -> null with one node appended per step.

Basic Implementation

basic.cpp
#include <iostream>

struct ListNode {
    int value;
    ListNode* next;
    explicit ListNode(int v) : value(v), next(nullptr) {}
};

int main() {
    int values[] = {10, 20, 30, 40};
    ListNode* head = nullptr;
    ListNode* tail = nullptr;
    for (int v : values) {
        ListNode* node = new ListNode(v);
        if (head == nullptr) {
            head = node;
        } else {
            tail->next = node;
        }
        tail = node;
    }
    ListNode* cur = head;
    while (cur != nullptr) {
        std::cout << cur->value << " -> ";
        cur = cur->next;
    }
    std::cout << "null" << std::endl;
    cur = head;
    while (cur != nullptr) {
        ListNode* n = cur->next;
        delete cur;
        cur = n;
    }
    return 0;
}

Complexity

  • Time: O(n) with a tail pointer
  • Space: O(n) for the chain

Implementation notes

  • C++: a small struct ListNode with raw ListNode* next pointers is the idiomatic Node. nullptr represents end-of-list honestly.
  • The replay never shows runtime pointer addresses; nodes are labelled node(<value>) and the chain view is rendered as 10 -> 20 -> ... -> null.
  • The trailing delete walk frees each node in the order it was built so the lesson stays honest about ownership without obscuring the build step.
node chain Each `ListNode` carries an `int value` and a `ListNode* next` pointer.