C Program to Count Nodes in a Linked List

C Program to Count Nodes in a Linked List

Counting the number of nodes in a linked list is a fundamental operation that provides insight into the size of the list. Knowing the list size is essential for implementing other operations such as insertion at a specific position, deletion, or validation. Learning both iterative and recursive approaches helps strengthen understanding of linked list traversal, recursion, and pointer management in C.

Understanding the Problem

The main challenge is to traverse the entire list from the head to the last node while keeping track of the number of nodes encountered. Both iterative and recursive methods must ensure that each node is counted exactly once without skipping or repeating any. Special cases, such as an empty list, should be handled correctly so that the function returns zero. Proper traversal and careful pointer handling are key to accurately determining the list’s length.

Program 1: Count Nodes (Iterative Approach)

This program demonstrates how to dynamically build a linked list and count the total number of nodes. It uses a simple counter variable and iterates through the list to determine its size. The insertAtEnd function allows adding elements to the list, while the display function helps visualize the current sequence of nodes.

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

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

Node *head = NULL;

// Function to insert node at the end
void insertAtEnd(int value) {

    Node *newNode = (Node*)malloc(sizeof(Node));
    newNode->data = value;
    newNode->next = NULL;

    if (!head) {
        head = newNode;
    } else {

        Node *temp = head;

        while (temp->next) {
            temp = temp->next;
        }

        temp->next = newNode;

    }

}

// Function to count nodes in the linked list
int countNodes() {

    int count = 0;
    Node *temp = head;

    while (temp) {
        count++;
        temp = temp->next;
    }

    return count;

}

// Function to display the list
void display() {

    if (!head) {
        printf("Linked List is empty\n");
        return;
    }

    Node *temp = head;

    printf("Linked List: ");

    while (temp) {
        printf("%d ", temp->data);
        temp = temp->next;
    }

    printf("\n");

}

int main() {

    insertAtEnd(10);
    insertAtEnd(20);
    insertAtEnd(30);

    display();

    int totalNodes = countNodes();
    printf("Total nodes in the linked list: %d\n", totalNodes);

    return 0;

}

This program effectively counts nodes by traversing the linked list from head to tail. Each iteration increments a counter to keep track of the total nodes. This approach works for both empty lists and lists with multiple nodes.

Program 2: Count Nodes (Recursive Approach)

This program demonstrates how to count the total number of nodes in a linked list using recursion. The insertAtEnd function builds the list dynamically, and the recursive function traverses each node to determine the size of the list.

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

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

Node *head = NULL;

// Function to insert node at the end
void insertAtEnd(int value) {

    Node *newNode = (Node*)malloc(sizeof(Node));
    newNode->data = value;
    newNode->next = NULL;

    if (!head) {
        head = newNode;
    } else {

        Node *temp = head;

        while (temp->next) {
            temp = temp->next;
        }

        temp->next = newNode;

    }

}

// Recursive function to count nodes
int countNodesRecursive(Node *node) {
    if (!node) return 0;
    return 1 + countNodesRecursive(node->next);
}

// Function to display the list
void display() {

    if (!head) {
        printf("Linked List is empty\n");
        return;
    }

    Node *temp = head;

    printf("Linked List: ");

    while (temp) {
        printf("%d ", temp->data);
        temp = temp->next;
    }

    printf("\n");

}

int main() {

    insertAtEnd(10);
    insertAtEnd(20);
    insertAtEnd(30);

    display();

    int totalNodes = countNodesRecursive(head);
    printf("Total nodes in the linked list: %d\n", totalNodes);

    return 0;

}

This recursive program counts nodes by visiting each node and returning 1 + the count of the rest of the list. It handles empty lists naturally and works for lists of any size, demonstrating a clean, elegant alternative to iterative counting.

FAQs

Q1: What is the time complexity of counting nodes in a linked list?
The time complexity is O(n) for both iterative and recursive methods, since every node must be visited exactly once.

Q2: Can this handle an empty list?
Yes, both approaches return zero when the list is empty, providing an accurate count without errors.

Q3: Can this method be adapted for a doubly linked list?
Yes, the same traversal logic works from head to tail in a doubly linked list.

Q4: Is additional memory required to count nodes?
The iterative method uses only a counter variable, so space complexity is O(1). The recursive method uses the call stack, so its space complexity is O(n).

Conclusion

Counting nodes in a linked list is a fundamental operation that can be implemented iteratively or recursively. Both methods traverse the list and increment a count to determine the total number of nodes. Proper traversal ensures accurate results for empty lists and lists of any size. Mastering this operation provides a foundation for more advanced linked list manipulations and algorithms.

References & Additional Resources

The following books and online resources provide both theoretical foundations and practical examples to help you understand linked list operations and dynamic memory allocation in C.

  1. Kernighan, B. W., & Ritchie, D. M. (1988). The C Programming Language (2nd Edition). Prentice Hall – Classic reference on C fundamentals, including pointers and memory, critical for linked list operations.
  2. Thareja, R. (2011). Data Structures Using C. Oxford University Press – Detailed coverage of linked lists and dynamic memory allocation techniques.
  3. GeeksforGeeks: Length of a Linked List – Step-by-step examples and explanations of counting the number of nodes in a linked list using both iterative and recursive approaches.
  4. Programiz: Singly Linked List Basics – Beginner-friendly guide covering fundamental concepts and operations.
  5. Tutorialspoint: What is Dynamic Memory Allocation in C? – Explanation of malloc(), calloc(), realloc(), and free() functions for memory management in linked lists.
  6. C Standard Library Documentation – Memory Management – Official reference for memory allocation and deallocation functions in C.
Scroll to Top