C program to count the number of nodes in a linked list
PROGRAM:
#include <stdio.h>#include <stdlib.h>
//Creating structure
struct node
{
int data;
struct node *link;
}*first=NULL;
//function prototypes
struct node * create(struct node *);
int cntlink(struct node *);
//main function
int main()
{
int count;
printf("\nEnter elements to create linked list\n");
first=create(first);
printf("\nLinked list created!\n");
count=cntlink(first);
printf("\nNo. of nodes in the linked list= %d\n",count);
return 0;
}
//function to create linked list
struct node * create(struct node *first)
{
struct node *new_node;
int choice=0;
do
{
new_node=(struct node *)malloc(sizeof(struct node));
printf("\nEnter an element\n");
scanf("%d",&new_node->data);
new_node->link=NULL;
if(first==NULL)
first=new_node;
else
{
new_node->link=first;
first=new_node;
}
printf("\nEnter 1 to continue, 0 to stop\n");
scanf("%d",&choice);
}while(choice==1);
return first;
}
//function to count no. of nodes in the linked list
int cntlink(struct node *first)
{
struct node *temp;
int cnt=0;
if(first==NULL)
return 0;
else if(first->link==NULL)
return 1;
else
{
temp=first;
while(temp!=NULL)
{
++cnt;
temp=temp->link;
}
return cnt;
}
}
OUTPUT:
Enter elements to create linked listEnter an element
10
Enter 1 to continue, 0 to stop
1
Enter an element
20
Enter 1 to continue, 0 to stop
1
Enter an element
30
Enter 1 to continue, 0 to stop
1
Enter an element
40
Enter 1 to continue, 0 to stop
1
Enter an element
50
Enter 1 to continue, 0 to stop
0
Linked list created!
No. of nodes in the linked list= 5