recent

Search an element in a Linked List (Recursive Method)

Recursive Method to Search an element in a Linked List:-

1) If head is NULL, return false(0).
2) If head's key is equal to  key, return true(1);
2) Else return search(head->next, key) (Function call Again).

#include<stdio.h>
#include<stdlib.h>

struct node{

int data;
struct node *next;
};

void insert(struct node **head,int new_data)
{
struct node *new_node;
new_node=(struct node*)malloc(sizeof(struct node));

new_node->data=new_data;
new_node->next=*head;
*head=new_node;

}

int search(struct node *head,int key)
{
if(head==NULL)
return 0;
if(head->data==key)
{
return 1;
}
return search(head->next,key);

}

main()
{

struct node *head;
head=(struct node*)malloc(sizeof(struct node));

insert(&head,1);
insert(&head,2);
insert(&head,3);
insert(&head,4);
int x;

search(head,1) ? printf("Found\n") : printf("Not Found\n");

search(head,8) ? printf("Found\n") : printf("Not Found\n");
}


Powered by Blogger.