A directory of Objective Type Questions covering all the Computer Science subjects. Here you can access and discuss Multiple choice questions and answers for various compitative exams and interviews.

C program to search for an element in the Linked List using recursion


Problem Description


This C Program uses recursive function & search for an element in a linked list. A linked list is an ordered set of data elements, each containing a link to its successor.


C program to search for an element in the Linked List using recursion - Source code
     
                
  /*
C program to search for an element in linked list
using Recursion
 */

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

struct node
{
    int n;
    struct node *next;
};

void generate_list(struct node **, int);
void search_list(struct node *, int, int);
void delete(struct node **);

int main()
{
    struct node *head;
    int key, num;

    printf("Enter the number of nodes you want in the list.");
    scanf("%d", &num);
    generate_list(&head, num);
    printf("\nEnter key to search: ");
    scanf("%d", &key);
    search_list(head, key, num);
    delete(&head);
}

void generate_list(struct node **head, int num)
{
    int i;
    struct node *temp;

    for (i = 0; i < num; i++)
    {
        temp = (struct node *)malloc(sizeof(struct node));
        temp->n = rand() % num;
        printf("%d    ", temp->n);
        if (*head == NULL)
        {
            *head = temp;
            (*head)->next = NULL;
        }
        else
        {
            temp->next = *head;
            *head = temp;
        }
    }
}

void search_list(struct node *head, int key, int index)
{
    if (head->n == key)
    {
        printf("Key found at Position: %d\n", index);
    }
    if (head->next == NULL)
    {
        return;
    }
    search_list(head->next, key, index - 1);
}

void delete(struct node **head)
{
    struct node *temp;
    while (*head != NULL)
    {
        temp = *head;
        *head = (*head)->next;
        free(temp);
    }
}

     
      

Program Output


Enter the number of nodes you want in the list.25
16    17    9    0    19    24    3    8    12    14    5    20    6    2    11    16    20    17    2    11    16    4    2    3    17
Enter key to search: 20
Key found at Position: 17
Key found at Position: 12