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

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;
}

The canonical values [10, 20, 30, 40] become one node per value. The head pointer names the first node; the tail pointer names the last node appended.

Step 1 - First node

After appending 10, both head and tail point at the same node.

Start of the chain: head and tail both reach node(10).headtailnode(10)null

Step 2 - Append through 30

Each append changes the old tail's next pointer, then moves tail to the new node.

After appending 20 and 30: tail names node(30).headnode(10)node(20)node(30)tailnull

Step 3 - Final chain

Appending 40 gives the lesson's pinned chain: head -> 10 -> 20 -> 30 -> 40 -> null.

Complete linked list for [10, 20, 30, 40].headnode(10)node(20)node(30)node(40)tailnull

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.