Course contentsShow
← C
Lesson 993 of 1,21914. Data Structures in CFree lesson

Prepending nodes to the head

Prepending nodes to the head

What you'll learn: How to efficiently add a new piece of data to the very beginning of a linked list.

The "Train Car" Analogy

Imagine a freight train where you are standing at the very front (the engine). If you want to add a new cargo car to the front, you don't just shove it in; there is a specific order of operations. First, you bring the new car in. Next, you hook the new car's rear coupler to the current engine. Finally, you declare that the new car is now the official "front" of the train.

In C, prepending is the most efficient way to grow a list because you don't have to walk through every single node to find the end. You just snap it onto the front and update your "head" pointer.

The Three-Step Process

To prepend a node, we follow these steps to ensure we don't "drop" the rest of the list into computer memory limbo:

  1. Allocate memory: Create a new node using malloc.
  2. Point to the old head: Set the new node's next pointer to wherever the current head is pointing. This links the new node to the existing chain.
  3. Update the head: Point the head pointer to our new node. The new node is now the official start.

Coding the Prepend

Here is how we implement this logic. Note that we pass a pointer to the head pointer (**head_ref) so we can modify the original head back in the main function.

#include <stdio.h>
#include <stdlib.h>

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

void prepend(struct Node** head_ref, int new_data) {
    // 1. Prepare the new node
    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
    new_node->data = new_data;

    // 2. Link the new node to the current list
    // Even if the list is empty (NULL), this works!
    new_node->next = (*head_ref);

    // 3. Move the head to point to the new node
    (*head_ref) = new_node;
}

int main() {
    struct Node* head = NULL; // Start with an empty list
    
    prepend(&head, 10); // List: 10 -> NULL
    prepend(&head, 20); // List: 20 -> 10 -> NULL
    
    return 0;
}

Why this order matters

If you flipped steps 2 and 3—pointing the head to the new node before linking the new node to the old list—you would lose the address of the rest of your list. The remaining nodes would still exist in memory, but you'd have no way to find them. This is called a memory leak. By always linking the new node to the old head first, you ensure the chain is never broken.

Key takeaway

Prepending is an O(1)O(1) operation that adds a node by linking it to the current head and then updating the head pointer.