Search an element in a Linked List Recursive
#include<stdio.h>
#include<stdlib.h>
struct node
{
char data;
struct node *next;
}*head;
void insert(int num)
{
struct node* temp;
temp=(struct node *)malloc(sizeof(struct node));
temp->data=num;
temp->next=NULL;
if(head==NULL)
{
head=temp;
}
else
{
struct node* temp1=head;
while(temp1->next!=NULL)
{
temp1=temp1->next;
}
temp1->next=temp;
}
}
void display()
{
struct node *temp2;
temp2=head;
while(temp2!=NULL)
{
printf("%d ",temp2->data);
temp2=temp2->next;
}
}
int search_the_element(struct node* temp,int n1)
{
if(temp==NULL)
return 0;
if(temp->data==n1)
return 1;
search_the_element(temp->next,n1);
}
int main()
{
int i,num;
int pos;
int n1,n2;
struct node *n;
head=NULL;
while(1)
{
printf("\nList Operations\n");
printf("===============\n");
printf("1.Insert\n");
printf("2.Display\n");
printf("3.Find the element in the linked list recursively\n");
printf("4.Exit\n");
printf("Enter your choice : ");
if(scanf("%d",&i)<=0){
printf("Enter only an Integer\n");
exit(0);
} else {
switch(i)
{
case 1: printf("Enter the number to insert : ");
scanf("%d",&num);
insert(num);
break;
case 2: if(head==NULL)
{
printf("List is Empty\n");
}
else
{
printf("Element(s) in the list are : ");
}
display(n);
break;
case 3:
printf("Enter the element to be searched\n");
scanf("%d",&n1);
if(search_the_element(head,n1))
printf("Element Found");
else
printf("Element not found\n");
break;
case 4:
return 0;
default: printf("Invalid option\n");
}
}
}
return 0;
}
No comments:
Post a Comment