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 thehead
node of the linked list. - Initialise an integer variable
count
aszero(0)
. - Traverse the linked list using
temp
and increment the variablecount
byone
untiltemp
becomesNULL
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;
};
void displayLL(struct node * head)
{
struct node * temp;
temp = head;
temp=head;
while(temp!=0)
{
printf("%d ",temp->data);
temp = temp->next;
}
}
void length(struct node *head)
{
struct node *temp = head;
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;
// Create Linked List //
printf("Enter the number of nodes in the list : ");
scanf("%d", &n);
if(n == 0)
{
printf("--------------------------------\n");
printf("Linked list cannot be empty");
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;
if(head == 0)
{
head = temp = newnode;
}
else
{
temp->next = newnode;
temp = newnode;
}
}
printf("--------------------------------\n");
printf("Original linked list : ");
displayLL(head);
length(head);
}
Top comments (0)