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.c
#include <stdio.h>
#include <stdlib.h>

typedef struct ListNode {
    int value;
    struct ListNode *next;
} ListNode;

int main(void) {
    int values[] = {10, 20, 30, 40};
    size_t n = sizeof(values) / sizeof(values[0]);
    ListNode *head = NULL;
    ListNode *tail = NULL;
    for (size_t i = 0; i < n; ++i) {
        ListNode *node = malloc(sizeof(ListNode));
        node->value = values[i];
        node->next = NULL;
        if (head == NULL) {
            head = node;
        } else {
            tail->next = node;
        }
        tail = node;
    }
    ListNode *cur = head;
    while (cur != NULL) {
        printf("%d -> ", cur->value);
        cur = cur->next;
    }
    printf("null\n");
    cur = head;
    while (cur != NULL) {
        ListNode *next = cur->next;
        free(cur);
        cur = next;
    }
    return 0;
}

Complexity

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

Implementation notes

  • C: a small typedef struct ListNode { int value; struct ListNode *next; } ListNode; pattern is the idiomatic Node. NULL 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 free walk releases 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 `struct ListNode *next` pointer.