C program to find multiple keys in a 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 *);
int search(struct node *,int);

//main function
int main()
{
    int key,count=0;
    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);
    count=search(first,key);
    if(count==0)
        printf("\nKey not found\n");
    else
        printf("\nNo. of key nodes found=%d\n",count);
    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 key nodes in the linked list
int search(struct node *first,int key)
{
    struct node *temp;
    int cnt=0;
    if(first==NULL)
        return cnt;
    else
    {
        temp=first;
        while(temp!=NULL)
        {
            if(temp->data==key)
            {
            printf("\nKey found!\n");
            cnt++;
            temp=temp->link;
            }
            else
            temp=temp->link;
        }
        return cnt;
    }
}



OUTPUT:

TRIAL 1:

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
10

Enter 1 to continue, 0 to stop
1

Enter  an element
30

Enter 1 to continue, 0 to stop
1

Enter  an element
10

Enter 1 to continue, 0 to stop
1

Enter  an element
40

Enter 1 to continue, 0 to stop
1

Enter  an element
10

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
10

Key found!

Key found!

Key found!

Key found!

No. of key nodes found=4



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

Popular Posts