Count number of nodes


 

Count number of nodes

This tutorial demonstrate how to count the number of nodes present in the linked list.

This tutorial demonstrate how to count the number of nodes present in the linked list.

Code:

# include <stdio.h>
# include <stdlib.h>
struct node
{
int data;
struct node *link;
};
struct node *insert(struct node * , int);
int countnode(struct node*);
void printlist (struct node *);

struct node *insert(struct node *p , int n)
{
	struct node *temp;
	if(p==NULL)
	{
		p=(struct node *)malloc(sizeof(struct node));
		if(p==NULL)
		{
			printf("Error Occurred\n");
			  exit(0);
		}
		 p-> data = n;
		 p-> link = NULL;
	 }
	 else
	 {
		temp = p;
		while (temp-> link!= NULL)
		 temp = temp-> link;
temp-> link =  (struct node *)malloc(sizeof(struct node));
		if(temp -> link == NULL)
		{
			printf("Error Occurred\n");
			exit(0);
		}
		temp = temp-> link;
		temp-> data = n;
		temp-> link = NULL;
	  }
	  return (p);
}


void printlist ( struct node *p  )
{
	printf("The data in the list are\n");
	while (p!= NULL)
	{
		printf("%d\t",p-> data);
		p = p-> link;
	}
}

int  countnode (struct node *p )
{
	int count=0;
	while (p != NULL)
	{
		 count ++;
		 p = p->link;
	}
		return(count);
}


void main()
{
	int n;
	int x;
	struct node *start = NULL ;
	printf("Enter number of nodes to be created \n");
	scanf("%d",&n);
	while ( n-- > 0 )
	{
		printf( "Enter the data for node\n");
		scanf("%d",&x);
		start = insert ( start ,x);
	}
	printlist ( start );
	n = countnode(start);
	printf("\nThe number of nodes in a list are: %d\n",n);
}

Output:

Download this code

Ads