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

Counting the elements in a circular doubly linked list

Below is the code to count the elements in a circular doubly linked list

#include <stdio.h>
#include <stdlib.h>
struct node{
struct node *prev;
int data;
struct node *next;
};
struct node *add_to_empty(int data){
struct node *temp=malloc(sizeof(struct node));
temp->prev=temp;
temp->data=data;
temp->next=temp;
return temp;
}
struct node *ad_end(struct node *tail,int ele){
struct node *newp=add_to_empty(ele);
if(tail==NULL){
return newp;
}else{
struct node *temp=tail->next;
newp->prev=tail;
newp->next=temp;
tail->next=newp;
temp->prev=newp;
tail=newp;
return tail;
}
}
void count(struct node *tail){
struct node *temp=tail->next;
int cnt=0;
while(temp!=tail){
temp=temp->next;
cnt++;
}cnt++;
printf("\nTotal number of elements: %d",cnt);
}
void print(struct node *tail){
if (tail == NULL) {
printf("Linked list is empty.\n");
return;
}

struct node *temp = tail->next;
do {
printf("%d ", temp->data);
temp = temp->next;
} while(temp != tail->next);
}

int main(){
struct node *tail=NULL;
tail=add_to_empty(20);
tail=ad_end(tail,60);
tail=ad_end(tail,30);
tail=ad_end(tail,50);
print(tail);
count(tail);
}

OUTPUT:

20 60 30 50
Total number of elements: 4