Count total number of elements in linked list
Simple C Program to count total number of elements in a linked list.
Related:
Count total number of nodes in linked list using recursion
/* Count total number of elements in linked list */ #include<stdio.h> #include<stdlib.h> struct Node { int data; struct Node *next; }; /* Create a new node to insert in linked list */ struct Node *CreateNode(int data) { struct Node *newNode=(struct Node*)malloc(sizeof(struct Node)); newNode->data=data; newNode->next=NULL; return newNode; } /* Add element at the beginning of linked list */ struct Node *push(struct Node *head, int n) { struct Node *temp=CreateNode(n); temp->next=head; head=temp; return temp; } /* Count total number of element in linked list */ /* If linked list is empty then this function will return 0 */ int CountElements(struct Node *head) { struct Node *temp=head; int count=0; while(temp!=NULL) { count++; temp=temp->next; } return count; } int main() { struct Node *head=NULL; printf("Total elements in linked list= %d\n",CountElements(head)); head=push(head,5); head=push(head,4); printf("Total elements in linked list= %d\n",CountElements(head)); head=push(head,3); head=push(head,2); head=push(head,1); printf("Total elements in linked list= %d\n",CountElements(head)); return 0; }
Related:
Count total number of nodes in linked list using recursion