C Program to Search for an Element in the Linked List using Recursion
Posted by Superadmin on July 06 2019 04:49:00

C Program to Search for an Element in the Linked List using Recursion

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.

 

Here is the source code of the C program to find an element in linked list. The C Program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C program to search for an element in linked list
  3.  */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6.  
  7. struct node
  8. {
  9.     int a;
  10.     struct node *next;
  11. };
  12.  
  13. void generate(struct node **, int);
  14. void search(struct node *, int, int);
  15. void delete(struct node **);
  16.  
  17. int main()
  18. {
  19.     struct node *head;
  20.     int key, num;
  21.  
  22.     printf("Enter the number of nodes: ");
  23.     scanf("%d", &num);
  24.     generate(&head, num);
  25.     printf("\nEnter key to search: ");
  26.     scanf("%d", &key);
  27.     search(head, key, num);
  28.     delete(&head);
  29. }
  30.  
  31. void generate(struct node **head, int num)
  32. {
  33.     int i;
  34.     struct node *temp;
  35.  
  36.     for (i = 0; i < num; i++)
  37.     {
  38.         temp = (struct node *)malloc(sizeof(struct node));
  39.         temp->a = rand() % num;
  40.         printf("%d    ", temp->a);
  41.         if (*head == NULL)
  42.         {
  43.             *head = temp;
  44.             (*head)->next = NULL;
  45.         }
  46.         else
  47.         {
  48.             temp->next = *head;
  49.             *head = temp;
  50.         }
  51.     }
  52. }
  53.  
  54. void search(struct node *head, int key, int index)
  55. {
  56.     if (head->a == key)
  57.     {
  58.         printf("Key found at Position: %d\n", index);
  59.     }
  60.     if (head->next == NULL)
  61.     {
  62.         return;
  63.     }
  64.     search(head->next, key, index - 1);
  65. }
  66.  
  67. void delete(struct node **head)
  68. {
  69.     struct node *temp;
  70.     while (*head != NULL)
  71.     {
  72.         temp = *head;
  73.         *head = (*head)->next;
  74.         free(temp);
  75.     }
  76. }

 

$ cc pgm11.c
$ a.out
Enter the number of nodes: 6
1    4    3    1    5    1
Enter key to search: 1
Key found at Position: 6
Key found at Position: 4
Key found at Position: 1