## DEV Community

Dhanashree Rugi

Posted on

For more such blogs visit " www.coderlogs.com "

For a given linked list, you are supposed to write a function that finds the length of that linked list.

Example 1 :

Input : Linked List : 4 6 8 2
Output : Length of List : 4

Example 2 :

Input : Linked List : 1 3 1 2 1
Output : Length of List : 5

Steps :

• Declare and initialise a temporary pointer `temp` as the `head` node of the linked list.
• Initialise an integer variable `count` as `zero(0)`.
• Traverse the linked list using `temp` and increment the variable `count` by `one` until `temp` becomes `NULL` i.e.,
``````while(temp != NULL)
{
count++;
temp = temp->next;
}
``````
• Return or print the variable `count` which gives the length of the list.

C program that finds the length of the given linked list.

``````#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

struct node
{
int data;
struct node * next;
};

{
struct node * temp;
while(temp!=0)
{
printf("%d ",temp->data);
temp = temp->next;
}
}

{
int count = 0;

while(temp != NULL)
{
count++;
temp = temp->next;
}
printf("\n--------------------------------\n");
printf("Length of linked list : %d", count);
}
int main()
{
struct node *head = 0, *newnode, *temp;
int n, choice, newdata;

printf("Enter the number of nodes in the list : ");
scanf("%d", &n);

if(n == 0)
{
printf("--------------------------------\n");
exit(0);
}

for(int i = 1; i<=n; i++)
{
newnode = (struct node *)malloc(sizeof(struct node));
printf("Enter the data%d : ", i);
scanf("%d", &newnode->data);
newnode->next = 0;
{
}
else
{
temp->next = newnode;
temp = newnode;
}
}
printf("--------------------------------\n");