Search Element in Single Linked List in C

Description

This program is used to search elements in a Single Linked List using C.


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

struct node
{
 int data;
 struct node* next;
};
struct node *head=NULL;

void create();
void search();
void print();
void main()
{
  int choice;
  do
  {
   printf("\n__MENU__\n1.Create List\n2.Search Element.\n3.Print the List\n4...EXIT...\n");
   printf("\nENTER your choice\n");
   scanf("%d",&choice);
   switch(choice)
   {
    case 1: create();break;
    case 2:search();break;
    case 3:print();break;
    case 4:printf("~~~~~~~THANK YOU~~~~~~~\n");break;
   default:printf("INVALID input !!!");break;   
  }
  }while(choice!=4);
}

void search()
{
 int a,i=1,value;
 struct node* temp;
 temp=head;
 printf("Enter element to be searched\n");
 scanf("%d",&value);
    if(temp->data==value)
    printf("\n%d is at position 1.\n ",value);
    else
    {
     while(temp->next!=NULL)
     {
      temp=temp->next;
      i++;
      if(temp->data==value)
      break;
     }
  if(temp->data==value)
  printf("\n%d is at position %d.\n ",value,i);
  else if(temp->next==NULL)
  printf("\nELEMENT NOT FOUND !!!\n");
 }
}

void create()
{
 int x, i,n;
 head=NULL;
 struct node* newnode,*temp;
 temp=head;
 printf("Enter no. of elements in the LIST \n");
 scanf("%d",&n);
 printf("Enter %d elements\n",n);
 for(i=0;i<n;i++)
 {
  temp=head; 
  newnode=(struct node*)malloc(sizeof(struct node*)); 
  scanf("%d",&x);
     newnode->data=x;
     if(head==NULL)
     {
      head=newnode;
      newnode->next=NULL;
     }
     else
  {
         while(temp->next!=NULL)
   temp=temp->next;
   temp->next=newnode;
   newnode->next=NULL; 
         }
 }
 print();
}

void print()
{
 struct node* temp;
 temp=head;
 if(head==NULL)
 printf("list is empty !!!\n\n");
 else
 {
  printf("\nLIST elements are\t");
  while(temp!=NULL)
  {
   printf("%d\t",temp->data);
   temp=temp->next;
  }
 }
}


OUTPUT

Search Output 1 Search Output 2

Labels: ,