Count total number of nodes in linked list using recursion
Simple C Program to count total number of node in a linked list using recursion. Count total number of nodes using iterative method.
In recursion function, If head node is pointing to NULL then return 0. If linked list contains nodes then return 1+recursion function. Add 1 while node is pointing NULL;
C Program:
In recursion function, If head node is pointing to NULL then return 0. If linked list contains nodes then return 1+recursion function. Add 1 while node is pointing NULL;
C Program:
#include<stdio.h> #include<stdlib.h> struct LNode{ int data; struct LNode *next; }; struct LNode *CreateNode(int data) { struct LNode *newNode=(struct LNode*)malloc(sizeof(struct LNode)); newNode->data=data; newNode->next=NULL; return newNode; } void push(struct LNode **head,int n) { struct LNode *temp=CreateNode(n); struct LNode *temp1=*head; if(*head==NULL) *head=temp; else { while(temp1->next!=NULL) { temp1=temp1->next; } temp1->next=temp; } } void PrintList(struct LNode *head) { struct LNode *temp=head; if(temp==NULL) { printf("List is empty\n"); return ; } while(temp!=NULL) { printf("%d ",temp->data); temp=temp->next; } }int CountNodes(struct LNode *head) { if(head==NULL) return 0; return 1+CountNodes(head->next); }int main() { struct LNode *head=NULL; printf("\nNodes = %d\n",CountNodes(head)); push(&head,8); push(&head,9); push(&head,10); push(&head,11); PrintList(head); printf("\nNodes = %d\n",CountNodes(head)); push(&head,13); printf("\nNodes = %d\n",CountNodes(head)); return 0; }