Skip to content
Home » Searching an element in a circular doubly linked list

Searching an element in a circular doubly linked list

Below is the code to search an element 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;
}
}
int search(struct node *tail,int ele){
struct node *temp=tail->next;
int index=0;
if(tail==NULL){
return -2;
}
do{
if(temp->data==ele){
return index;
}temp=temp->next;
index++;
}while(temp!=tail->next);
return -1;
}
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);
int a=search(tail,30);
if(a==-2){
printf("\nList is empty");
}else if(a==-1){
printf("\nElement is not found");
}else{
printf("\nElement is found at %d",a);
}
}

OUTPUT:

20 60 30 50
Element is found at 2