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

Searching an element in a circular singly linked list

Below is the code to search an element 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;
}
int search(struct node *tail,int ele){
struct node *temp=tail->link;
int index=0;
if(tail==NULL){
return -2;
}
do{
if(temp->data==ele){
return index;
}temp=temp->link;
index++;
}while(temp!=tail->link);
return -1;
}
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);
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 15 75 60 45
Element is not found