Lesson 1 of 14

The Node

Linked Lists

A linked list is a sequence of nodes where each node holds a value and a pointer to the next node:

[1] -> [2] -> [3] -> [4] -> NULL

Unlike arrays, linked lists don't store elements in contiguous memory. Each node lives wherever malloc puts it — they're connected only by pointers.

This makes inserting and deleting at the front O(1), but random access O(n).

The Node Struct

struct Node {
    int val;
    struct Node *next;
};

next points to the following node. The last node's next is NULL.

Creating Nodes

Allocate each node with malloc and initialize its fields:

struct Node *new_node(int val) {
    struct Node *n = (struct Node *)malloc(sizeof(struct Node));
    n->val = val;
    n->next = NULL;
    return n;
}

Building a List Manually

struct Node *head = new_node(1);
head->next = new_node(2);
head->next->next = new_node(3);
// [1] -> [2] -> [3] -> NULL

Your Task

Implement struct Node *new_node(int val) that allocates a node with the given value and next = NULL. Create a node with value 10 and print its value.

TCC compiler loading...
Loading...
Click "Run" to execute your code.