recent

Find Length of a Linked List(Recursive Method)

Recursive Method to Find Length of a Linked List:-

1) If head->next is NULL, return 0.
2) Else return 1 + getCount(head->next)

#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;

}

int count(struct node *head)
{
if(head->next==0)
return 0;

else
return 1+count(head->next);

}

main()
{

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

insert(&head,1);
insert(&head,2);
insert(&head,3);
insert(&head,4);
insert(&head,11);
insert(&head,21);
insert(&head,31);
insert(&head,41);

count(head);

printf("Number of Node:%d\n",count(head));
}
Powered by Blogger.