Find Length of a Linked List (Iterative method)

Iterative Method to Find Length of a Linked List:-

1) Initialize count as 0
2) Initialize a node pointer, current = head.
3) Do following while current->next is not NULL
     a) current = current -> next
     b) count++;
4) Print 'count'.

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

struct node{

int data;
struct node *next;
};

void insert(struct node **head,int new_data)
{
struct node *new_node;
new_node=(struct node*)malloc(sizeof(struct node));

new_node->data=new_data;
new_node->next=*head;
*head=new_node;

}

void count(struct node *head)
{
int count=0;
struct node *current;
current=head;
while(current->next!=0)
{
current=current->next;
count++;
}
printf("Number of Node:%d\n",count);
}

main()
{

struct node *head;
head=(struct node*)malloc(sizeof(struct node));

insert(&head,1);
insert(&head,2);
insert(&head,3);
insert(&head,4);

count(head);

}

Related Posts