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

Searching an element in a singly linked list

Below is the code to search an element in a single linked list


#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *link;
};
struct node *head;
void append(int element){
struct node *new_node=(struct node *)malloc(sizeof(struct node));
new_node->data=element;
new_node->link=NULL;
if(head==NULL){
head=new_node;
}
else{
struct node *current=head;
while(current->link!=NULL){
current=current->link;
}
current->link=new_node;
}
}
void srch(int key){
int count=0;
struct node *ptr;
ptr=head;
while(ptr->link!=NULL){
if(ptr->data==key){
count=1;
}
ptr=ptr->link;
}
count==0?printf("%d is not found\n",key):printf("%d is found\n",key);
}
int main(){
append(10);
append(20);
append(50);
append(60);
srch(2);
srch(20);
}

OUTPUT:

2 is not found
20 is found