C program to search a key node in linked list
PROGRAM:
#include <stdio.h>#include <stdlib.h>
//Creating structure
struct node
{
int data;
struct node *link;
}*first=NULL;
//function prototypes
struct node * create(struct node *);
void search(struct node *,int);
//main function
int main()
{
int key;
printf("\nEnter elements to create linked list:\n");
first=create(first);
printf("\nLinked list created!\n");
printf("\nEnter key to be searched in the linked list\n");
scanf("%d",&key);
search(first,key);
return 0;
}
//function to create linked list
struct node * create(struct node *first)
{
struct node *new_node;
int choice=0;
do
{
new_node=(struct node *)malloc(sizeof(struct node));
printf("\nEnter an element\n");
scanf("%d",&new_node->data);
new_node->link=NULL;
if(first==NULL)
first=new_node;
else
{
new_node->link=first;
first=new_node;
}
printf("\nEnter 1 to continue, 0 to stop\n");
scanf("%d",&choice);
}while(choice==1);
return first;
}
//function to search keynode in the linked list
void search(struct node *first,int key)
{
struct node *temp;
if(first==NULL)
printf("\nKey not found\n");
else
{
temp=first;
while(temp!=NULL)
{
if(temp->data==key)
{
printf("\nKey found!\n");
return;
}
else
temp=temp->link;
}
printf("\nKey not found!\n");
}
}
OUTPUT:
TRIAL1:
Enter elements to create linked list:Enter an element
10
Enter 1 to continue, 0 to stop
1
Enter an element
20
Enter 1 to continue, 0 to stop
1
Enter an element
30
Enter 1 to continue, 0 to stop
1
Enter an element
40
Enter 1 to continue, 0 to stop
1
Enter an element
50
Enter 1 to continue, 0 to stop
0
Linked list created!
Enter key to be searched in the linked list
40
Key found!
TRIAL 2:
Enter elements to create linked list:Enter an element
10
Enter 1 to continue, 0 to stop
1
Enter an element
20
Enter 1 to continue, 0 to stop
1
Enter an element
30
Enter 1 to continue, 0 to stop
1
Enter an element
40
Enter 1 to continue, 0 to stop
1
Enter an element
50
Enter 1 to continue, 0 to stop
0
Linked list created!
Enter key to be searched in the linked list
60
Key not found!