C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Data Structures in C

Count Total Nodes in a Linked List

C Program: Count Total Nodes in a Linked List

C

#include <stdio.h>

#include <stdlib.h>

 

// Structure for a node

struct Node {

    int data;

    struct Node *next;

};

 

// Function to create linked list

struct Node* createList(int n) {

    struct Node *head = NULL, *temp, *newNode;

    int data, i;

 

    for (i = 1; i <= n; i++) {

        newNode = (struct Node*)malloc(sizeof(struct Node));

        if (newNode == NULL) {

            printf("Memory allocation failed!\n");

            exit(0);

        }

 

        printf("Enter data for node %d: ", i);

        scanf("%d", &data);

        newNode->data = data;

        newNode->next = NULL;

 

        if (head == NULL)

            head = newNode;

        else

            temp->next = newNode;

 

        temp = newNode;

    }

    return head;

}

 

// Function to display linked list

void displayList(struct Node *head) {

    struct Node *temp = head;

    if (head == NULL) {

        printf("\nList is empty.\n");

        return;

    }

 

    printf("\nLinked List: ");

    while (temp != NULL) {

        printf("%d -> ", temp->data);

        temp = temp->next;

    }

    printf("NULL\n");

}

 

// Function to count total nodes

int countNodes(struct Node *head) {

    int count = 0;

    struct Node *temp = head;

 

    while (temp != NULL) {

        count++;

        temp = temp->next;

    }

 

    return count;

}

 

int main() {

    struct Node *head = NULL;

    int n, total;

 

    printf("Enter number of nodes: ");

    scanf("%d", &n);

 

    head = createList(n);

 

    displayList(head);

 

    total = countNodes(head);

    printf("\nTotal number of nodes = %d\n", total);

 

    return 0;

}

Output

 
OUTPUT :

Enter number of nodes: 5
Enter data for node 1: 10
Enter data for node 2: 20
Enter data for node 3: 30
Enter data for node 4: 40
Enter data for node 5: 50

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

Total number of nodes = 5

Explanation

Step

Description

1

Create a linked list dynamically using malloc().

2

Traverse the linked list from head to NULL.

3

Increment a counter for each node visited.

4

Return the total count to the main function.