Mental Model
Add a new item right at the start of the list so it becomes the new first item.
Analogy: Imagine putting a new book on the front of a line of books on a shelf, pushing all others back.
head -> 1 -> 2 -> 3 -> null
head -> 1 -> 2 -> 3 -> null
new_node(0) -> null head -> 1 -> 2 -> 3 -> null
new_node(0) -> 1 -> 2 -> 3 -> null head -> 1 -> 2 -> 3 -> null
head -> 0 -> 1 -> 2 -> 3 -> null
head -> 0 -> 1 -> 2 -> 3 -> null
#include <stdio.h> #include <stdlib.h> // Node structure typedef struct Node { int data; struct Node* next; } Node; // Insert at beginning function void insertAtBeginning(Node** head_ref, int new_data) { // Create new node Node* new_node = (Node*)malloc(sizeof(Node)); new_node->data = new_data; // Link new node to current head new_node->next = *head_ref; // Update head to new node *head_ref = new_node; } // Print list function void printList(Node* node) { while (node != NULL) { printf("%d -> ", node->data); node = node->next; } printf("null\n"); } int main() { // Create initial list 1->2->3->null Node* head = (Node*)malloc(sizeof(Node)); head->data = 1; head->next = (Node*)malloc(sizeof(Node)); head->next->data = 2; head->next->next = (Node*)malloc(sizeof(Node)); head->next->next->data = 3; head->next->next->next = NULL; printf("Original list: "); printList(head); // Insert 0 at beginning insertAtBeginning(&head, 0); printf("After inserting 0 at beginning: "); printList(head); return 0; }
Node* new_node = (Node*)malloc(sizeof(Node));new_node->data = new_data;new_node->next = *head_ref;*head_ref = new_node;new_node->next = *head_ref;