Singly Linked List in C (Full CRUD & Memory Management)

Linked Lists in C — conceptual cover illustration
Linked Lists in C — conceptual cover illustration

A singly linked list is a fundamental dynamic data structure of nodes connected by forward pointers. Learn how to allocate nodes with malloc, insert at head, traverse, and free memory in C.

A singly linked list is a dynamic linear data structure composed of nodes, where each node contains a payload and a pointer to the next node in the heap. Unlike arrays, linked lists can grow and shrink dynamically without expensive contiguous memory reallocations.

Manipulating linked list nodes in C requires meticulous pointer management. Inserting a node at the head runs in O(1) time by pointing the new node's next pointer to the current head and updating the head pointer.

Traversing and deleting nodes requires keeping track of the current node and its predecessor. Every node allocated with malloc() must be explicitly deallocated with free() to prevent long-term memory leaks.

Interactive Runnable C Implementation

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

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

Node* insertHead(Node *head, int val) {
    Node *newNode = (Node *)malloc(sizeof(Node));
    newNode->data = val;
    newNode->next = head;
    return newNode;
}

void printList(Node *head) {
    Node *curr = head;
    while (curr != NULL) {
        printf("%d -> ", curr->data);
        curr = curr->next;
    }
    printf("NULL\n");
}

void freeList(Node *head) {
    Node *curr = head;
    while (curr != NULL) {
        Node *temp = curr;
        curr = curr->next;
        free(temp);
    }
}

int main() {
    Node *head = NULL;
    head = insertHead(head, 30);
    head = insertHead(head, 20);
    head = insertHead(head, 10);

    printf("Linked List: ");
    printList(head);

    freeList(head);
    return 0;
}

Open example in compiler

Expected Output

Linked List: 10 -> 20 -> 30 -> NULL

Frequently Asked Questions

What is the time complexity of Singly Linked List Implementation in C?

O(1) insertion at head with predictable asymptotic runtime behavior.

Related examples