Here we’ll see how to write a C program to print the length of a linked list. The function get_length() takes a linked list as input and returns the length of it. First we’ll create a linked list and pass that list to the get_length() function to print the length of the list.
#include <stdio.h>
#include <stdlib.h>
struct node{
int val;
struct node *next;
};
int get_length(struct node *head) {
int len = 0;
while(head) {
len++;
head = head->next;
}
return len;
}
void print_list(struct node *head)
{
printf("H->");
while(head)
{
printf("%d->", head->val);
head = head->next;
}
printf("|||\n\n");
}
void insert_front(struct node **head, int value)
{
struct node * new_node = NULL;
new_node = (struct node *)malloc(sizeof(struct node));
if (new_node == NULL)
{
printf("Failed to insert element. Out of memory");
}
new_node->val = value;
new_node->next = *head;
*head = new_node;
}
int main()
{
struct node * head = NULL;
/*Creating the linked list*/
insert_front(&head, 16);
insert_front(&head, 83);
insert_front(&head, 89);
insert_front(&head, 12);
insert_front(&head, 67);
insert_front(&head, 20);
insert_front(&head, 2);
printf("Linked List: ");
print_list(head);
printf("Length of the Linked List: %d.\n", get_length(head));
return 0;
}
The get_length() function traverses the list until it reaches to NULL (end). For every node it increments the variable len and finally returns that.
Here is the output of the above program.
Linked List: H->2->20->67->12->89->83->16->|||
Length of the Linked List: 7.