C program to search an element in linked list.

Posted by Mangesh on August 12, 2018

Description:

In linked list we traversal from head towards tail so for searching an element we shall just traversal and check the data with key value. If the data match any of the element then the element is found, else the element is not found.

Program :

#include<stdio.h>
#include<conio.h>
typedef struct node
{
  int data;
  struct node *next;
} node;
void display(node *list)
{
  int count = 0;
  printf("\nElements in linked list : ");
  while(list != NULL)
  {
    count++;
    printf("  %d",list->data);
    list = list->next;
  }
  printf("\nTotal node in linked list is %d.",count);
}
void search(node *list,int key)
{
  int j=0;
  int flag=1;
  while(list != NULL)
  {
    j++;
    if(list->data==key)
    {
      flag=0;
      printf("\n%d found in location %d.",key,j);
    }
    list = list->next;
  }
  if(flag)
  {
    printf("\n%d not found.",key);
  }
}

void main()
{
  int key;
  node *head, *tail;
  char character ='y';
  head = (node *) malloc (sizeof(node));
  clrscr();
  tail = head;
  while(character == 'y'){
  printf("\nEnter the element value : ");
  scanf("%d",&tail->data);
  printf("Do you want to add more element (y/n) : ");
  scanf("%s",&character);
  if(character=='y')
  {
    tail->next =  (node *) malloc(sizeof(node));
    tail = tail->next;
  }
  else
    tail->next=NULL;
  }
  display(head);
  printf("\nEnter element to search : ");
  scanf("%d",&key);
  search(head,key);
getch();
}

Output:

search in a linked list executed and tested in turbo c++ 3.2

Written with from Mangesh.

Related Post
1 C program to create singly linked list.
2 C program to display elements of linked list in reverse order.
3 C program to count number of node in linked list.
4 C program to print a linked list in reverals order.
5 C program to search an element in linked list.
Latest Post
1 C program to implement Queue using linked list.
2 C program for binary search tree (BST).
3 C program to search an element in linked list.
4 C program for postorder traversal in binary tree.
5 C program for preorder traversal in binary tree.