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 (address of next node).
In linked list, elements are not stored at contiguous memory locations.
You can check this video tutorial on linked list in which i have explained what is linked list? Array vs linked list.
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
Programming Video Tutorials on Linked List
C Program to Count Number of Nodes in a Linked List
In this example, we write a program in c to create a singly linked list of n nodes and count the number of nodes.
What is the time complexity to count the number of elements in the linked list?
The time complexity to count number of elements in linked list is O(n).
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