Skip to content

What is a Node?

A node is the building block of a linked list. Every node contains two things:

  • The data we want to store
  • A pointer to the next node

In C

c
typedef struct Node {
    int data;
    struct Node *next;
} Node;

int data is the actual data stored in each Node (for this example, it's an integer).

struct Node *next is a raw pointer, a 64-bit integer representing a memory address, that either points to the next node or is NULL if there is no next node.

WARNING

C doesn't know if next points to a valid node, uninitialized junk memory, or NULL. Dereferencing a NULL pointer will crash the program (Segfault).

In Rust

rust
struct Node {
    data: i32,
    next: Option<Box<Node>>,
}

data: i32 is the actual data stored in each Node, just like in C.

Option<Box<Node>> is Rust's way of representing struct Node * in C, but safer.

  • Box<T> is a heap-allocated pointer (a type of smart pointer). Unlike malloc, the memory is automatically freed when the Box goes out of scope. No manual cleanup needed!
  • Option<T> is an enum that's either Some(value) or None. This forces us to explicitly handle both cases.

What is T?

The T in Box<T> and Option<T> is a generic type placeholder. It means these types can hold any type, like integers, structs, strings, and etc. Here, T is the struct Node.

TIP

Unlike in C, the Rust compiler forces us to handle None before we can access the value inside. This prevents null pointer crashes by catching the error at compile time instead of runtime.

Key Difference

CRust
Pointer Typestruct Node *nextOption<Box<Node>>
Valid Pointeralways valid pointerSome(Box<Node>)
NullabilityNULLNone
Deallocationfree()Automatic

Personal study notes for learning data structures