DEV Community

Dhanashree Rugi
Dhanashree Rugi

Posted on

Length of Linked List.

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
image

Example 2 :

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

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;
 }
Enter fullscreen mode Exit fullscreen mode
  • 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);
}
Enter fullscreen mode Exit fullscreen mode

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay