This C program, using iteration, searches 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 search for an element in a linked list. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C Program to Search for an Element in the Linked List without
* using Recursion
*/
#include <stdio.h>
#include <stdlib.h>
struct node
{
int a;
struct node *next;
};
void generate(struct node **, int);
void search(struct node *, int);
void delete(struct node **);
int main()
{
struct node *head = NULL;
int key, num;
printf("Enter the number of nodes: ");
scanf("%d", &num);
printf("\nDisplaying the list\n");
generate(&head, num);
printf("\nEnter key to search: ");
scanf("%d", &key);
search(head, key);
delete(&head);
return 0;
}
void generate(struct node **head, int num)
{
int i;
struct node *temp;
for (i = 0; i < num; i++)
{
temp = (struct node *)malloc(sizeof(struct node));
temp->a = rand() % num;
if (*head == NULL)
{
*head = temp;
temp->next = NULL;
}
else
{
temp->next = *head;
*head = temp;
}
printf("%d ", temp->a);
}
}
void search(struct node *head, int key)
{
while (head != NULL)
{
if (head->a == key)
{
printf("key found\n");
return;
}
head = head->next;
}
printf("Key not found\n");
}
void delete(struct node **head)
{
struct node *temp;
while (*head != NULL)
{
temp = *head;
*head = (*head)->next;
free(temp);
}
}
$ gcc search_iter.c -o search_iter $ a.out Enter the number of nodes: 10 Displaying the list 3 6 7 5 3 5 6 2 9 1 Enter key to search: 2 key found
Sanfoundry Global Education & Learning Series – 1000 C Programs.
advertisement
advertisement
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
If you wish to look at other example programs on Linked List, go to Linked List. If you wish to look at programming examples on all topics, go to C Programming Examples.
Next Steps:
- Get Free Certificate of Merit in Data Structure I
- Participate in Data Structure I Certification Contest
- Become a Top Ranker in Data Structure I
- Take Data Structure I Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Practice Programming MCQs
- Apply for Computer Science Internship
- Buy Data Structure Books
- Practice Design & Analysis of Algorithms MCQ
- Apply for Information Technology Internship