Singly Linked List in C: Operations, Pros/Cons & Real-World Uses

singly linked list is a linear data structure where each element (node) contains data and a pointer to the next node. Unlike arrays, nodes aren’t stored contiguously in memory, enabling dynamic memory usage and efficient insertions/deletions.

πŸ’‘ Real-world analogy: Think of a treasure hunt where each clue points to the next location.

Data structure: Singly linked list
Singly Linked List : Memory representation

Node Structure Explained

struct node {
    int data            // Data (int, char, etc.)
    struct node* next;  // Pointer to next node
};
  • data: Actual value (int, char, struct, etc.)
  • next: Memory address of next node (or NULL for last node)
  • head: Pointer to first node (entry point)

Key Advantages & Disadvantages

ProsCons
Dynamic memory allocationNo random access (e.g., <code class="language-c">arr[5])
O(1) insertion/deletion at headExtra memory for pointers
Efficient for stacks/queues implementationTraversal is O(n)

πŸ’‘ Key Insight: Use linked lists when you need frequent insertions/deletions, dynamic sizing, or memory efficiency. Avoid them for random access tasks (e.g., binary search).

Singly Linked List – Core operations in C

1. Create a Node

struct node* createNode(int data) {
    struct Node* newNode = (struct node*) malloc(sizeof(struct node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

2. Insert at Head – O(1)

void insertFront(struct node** head, int data) {
    struct node* newNode = createNode(data);
    newNode->next = *head;
    *head = newNode;
}

3. Insert at End – O(n)

void insertEnd(struct node** head, int data) {
    struct node* newNode = createNode(data);
    if (*head == NULL) {
        // List is empty
        *head = newNode;
    } else {
        struct node* temp = *head;
        // Traverse till end of list
        while (temp->next != NULL) 
            temp = temp->next;
        temp->next = newNode;
    }
}

4. Delete First Node – O(1)

void deleteFront(struct node** head) {
    if (*head == NULL) {
        // List is empty, nothing to delete
        return;
    }
    struct node* temp = *head;
    *head = (*head)->next;
    free(temp);
}

5. Traverse List

void printList(struct node* head) {
    while (head != NULL) {
        printf("%d β†’ ", head->data);
        head = head->next;
    }
    printf("\n");
}

Real-World Applications

  • Undo/Redo: Stores editor states in text processors
  • Hash Tables: Handles collisions using chaining
  • Polynomial Representation: Stores coefficients and exponents

Singly vs. Doubly Linked Lists

FeatureSingly LinkedDoubly Linked
Pointers per Node1 (next)2 (prevnext)
Memory OverheadLowerHigher
TraversalForward onlyBidirectional
Use CasesStacks, simple queuesBrowser history, editors

πŸ™‡β€β™‚οΈ Doubly linked list: Pros/cons, applications, implementation.
πŸ™‡β€β™‚οΈ Arrays vs. Linked Lists