Write a c program to count number of nodes in a linked list. In this tutorial, We are going to write a c code to count the number of nodes in a linked list.
What is Linked List?
A linked list is a collection of nodes, each pointing to next node by means of a pointer. In linked list, each node consists of two parts, a data and a pointer to next node.
An Algorithm to Count Number of Nodes in a Linked List
i) Take a count variable and initialize it to zero, count = 0.
ii) Traverse a linked list and increment a count variable.
iii) When a node points to a null, it means we reach at end of a linked list then return the value of a count variable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | void print(){ /* temp pointer points to head */ struct node* temp = head; /* Initialize count variable */ int count=0; /* Traverse the linked list and maintain the count */ while(temp != NULL){ temp = temp->next; /* Increment count variable. */ count++; } /* Print the total count. */ printf("\n Total no. of nodes is %d",count); } |
Programming Questions on Linked List.
Objective Questions for Practice
C Program to Count Number of Nodes in a Linked List
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | #include <stdio.h> //linked list node structure struct node{ int data; struct node* next; }; struct node* head; void insert(int data){ /* Allocate memory*/ struct node* temp = (struct node*)malloc(sizeof(struct node)); temp->data = data; temp->next = head; head = temp; } void print(){ struct node* temp = head; int count=0; /* Traverse the linked list and maintain the count. */ while(temp != NULL){ temp = temp->next; count++; } printf("\n Total no. of nodes is %d",count); } void main(){ head = NULL; insert(2); insert(4); /* calling print function to print the count of node. */ print(); } |
The time complexity to count the number of nodes in a linked list is O(n).
C Program to Insert Node at the head of a Linked List