Search an element/item from link list in C
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *create_linklist(int arr[],int size)
{
struct node *head=NULL,*temp=NULL,*current=NULL;
for(int i=0;i<size;i++)
{
temp=(struct node *)malloc(sizeof(struct node));
temp->data=arr[i];
temp->next=NULL;
if(head==NULL)
{
head=temp;
current=temp;
}
else
{
current->next=temp;
current=temp;
}
}
return head;
};
int search_item(struct node *head,int item)
{
int r=1;
while(head!=NULL)
{
if(head->data==item)
{
return r;
}
r++;
head=head->next;
}
return -1;
}
int main()
{
int a[]={10,20,30,40,50,50};
struct node *head=NULL;
head=create_linklist(a,6);
int ans=search_item(head,50);
printf("%d\n",ans);
return 0;
}
0 Comments