Here we are going to write a c program to search for a value in singly linked list.
Searching for a value in a singly linked list means to check whether a given value is present in the DATA part of the node or not. If present we will return true otherwise false.
First we will take a pointer variable temp and initialize it with HEAD i.e., now temp points to the first node of the linked list. In while loop, we will traverse through the linked list till we reach to the node which contains the given value. If we find such node then we will return true otherwise false.
C program to search for a given value in singly linked list -
#include <stdio.h>
#include <malloc.h>
#include <stdbool.h>
struct node
{
int data;
struct node* next;
};
void insertatend(struct node** head,int n)
{
struct node* val=(struct node*)malloc(sizeof(struct node));
val->data=n;
val->next=NULL;
if(*head==NULL)
{
*head=val;
return;
}
struct node* t=*head;
while(t->next!=NULL)
{
t=t->next;
}
t->next=val;
}
bool search(struct node* head)
{
int n;
printf("Enter the value you want to search: ");
scanf("%d",&n);
struct node* temp=head;
while(temp->next!=NULL)
{
temp=temp->next;
if(temp->data==n)
{
return 1;
}
}
return 0;
}
void display(struct node* head)
{
struct node* t=head;
while(t!=NULL)
{
printf("%d => ",t->data);
t=t->next;
}
printf("NULL \n");
}
int main()
{
struct node* head=NULL;
struct node* ll;
int arr[10]={1,2,3,4,5,6,7,8,9,10};
for(int i=0;i<10;i++)
{
insertatend(&head,arr[i]);
}
display(head);
printf("%d",search(head));
// display(head);
return 0;
}Output-
1 => 2 => 3 => 4 => 5 => 6 => 7 => 8 => 9 => 10 => NULL
Enter the value you want to search: 8
1
1 => 2 => 3 => 4 => 5 => 6 => 7 => 8 => 9 => 10 => NULL
Enter the value you want to search: 11
0
Post a Comment
If you have any doubts, please let me know