Mental Model
Add a new item at the start of a linked list by making it point to the current first item.
Analogy: Imagine adding a new book on top of a stack of books; the new book becomes the first one you see.
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> // Define node structure struct Node { int data; struct Node* next; }; // Push function to add node at start void push(struct Node** head_ref, int new_data) { // Create new node struct Node* new_node = (struct Node*)malloc(sizeof(struct 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; } // Function to print list void printList(struct Node* node) { while (node != NULL) { printf("%d -> ", node->data); node = node->next; } printf("null\n"); } int main() { // Start with list 1->2->3->null struct Node* head = NULL; // Push 3 push(&head, 3); // Push 2 push(&head, 2); // Push 1 push(&head, 1); // Print original list printList(head); // Push 0 at start push(&head, 0); // Print updated list printList(head); return 0; }
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));new_node->next = *head_ref;*head_ref = new_node;new_node->next = *head_ref;