Skip to content
Home » Counting the elements in a circular singly linked list

Counting the elements in a circular singly linked list

Below is the code to count the elements present in a circular singly linked list.

#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *link;
};
struct node *addToEmpty(struct node *tail,int ele){
struct node *temp=malloc(sizeof(struct node));
temp->data=ele;
temp->link=temp;
return temp;
}
void print(struct node *tail){
struct node *temp=tail->link;
do{
printf("%d ",temp->data);
temp=temp->link;
}while(temp!=tail->link);
}
struct node *at_beg(struct node *tail,int ele){
struct node *temp=malloc(sizeof(struct node));
temp->data=ele;
temp->link=NULL;
temp->link=tail->link;
tail->link=temp;
return tail;
}
void count(struct node *tail){
struct node *temp=tail->link;
int cnt=0;
while(temp!=tail){
temp=temp->link;
cnt++;
}cnt++;
printf("\nTotal number of elements: %d",cnt);
}
int main(){
struct node *tail=NULL;
tail=addToEmpty(tail,45);
tail=at_beg(tail,60);
tail=at_beg(tail,75);
tail=at_beg(tail,15);
tail=at_beg(tail,20);
print(tail);
count(tail);
}

OUTPUT:

20 15 75 60 45
Total number of elements: 5