C Example Code2026-03-202 min read
Implement a Singly Linked List in C with dynamic memory allocation (malloc/free). Full code for node insertion, deletion, and traversal.
What is a Singly Linked List?
A Singly Linked List is a linear data structure where elements (nodes) are stored in heap memory. Each node contains:
data: The value stored in the node.next: A pointer pointing to the next node in the sequence.
Complete C Implementation
c (ISO Standard)#include <stdio.h> #include <stdlib.h> typedef struct Node { int data; struct Node *next; } Node; Node* createNode(int value) { Node *newNode = (Node*)malloc(sizeof(Node)); if (newNode == NULL) { fprintf(stderr, "Memory allocation failed.\n"); exit(EXIT_FAILURE); } newNode->data = value; newNode->next = NULL; return newNode; } void insertAtHead(Node **head, int value) { Node *newNode = createNode(value); newNode->next = *head; *head = newNode; } void printList(const Node *head) { const Node *current = head; while (current != NULL) { printf("%d -> ", current->data); current = current->next; } printf("NULL\n"); } void freeList(Node *head) { Node *temp; while (head != NULL) { temp = head; head = head->next; free(temp); } } int main() { Node *head = NULL; printf("Building Singly Linked List in C:\n"); insertAtHead(&head, 40); insertAtHead(&head, 30); insertAtHead(&head, 20); insertAtHead(&head, 10); printList(head); freeList(head); return 0; }
Sample Output
text (ISO Standard)Building Singly Linked List in C: 10 -> 20 -> 30 -> 40 -> NULL
Complexity Analysis
- Insert at Head:
O(1)constant time. - Traversal & Search:
O(n)linear time. - Space Overhead: Requires 1 pointer per node on 64-bit systems (8 bytes per pointer).
Related Data Structures & Guides
- Master structures and pointer members in Structures in C.
- Master dynamic memory in Pointers in C.