Search Node in Linked List


In order to search particular node in a linked list we have to traverse from first node to last node in a linked list and compare the search value against each node in a linked list. Whenever a node is found we set the flag to indicate successful search.

Algorithm to Search Node in Linked List


Step 1: FLAG = 0
           SAVE=FIRST
Step 2: Repeat step 3 while SAVE ≠ NULL
Step 3: If SAVE->INFO = X then
           FLAG = 1
           SAVE=SAVE->LINK
           Else
           SAVE=SAVE->LINK
Step 4: If FLAG = 1 then
           Write “Search is Successful”
           Else
           Write “Search is not successful”
Step 5: Exit


     

Program to Search Node in Linked List


#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node
{
      int info;
      struct node *link;
};
struct node *FIRST;
void createlist()
{
      char ch;
      printf("Enter n for break\n");
      ch=getchar();
      while(ch!='n')
      {
      struct node *NEW_NODE,*SAVE;int x;
       NEW_NODE=(struct node *)malloc(sizeof(struct node));
      printf("Enter Data:");
      scanf("%d",&x);
      NEW_NODE->info=x;
      if(FIRST==NULL)
      {
         NEW_NODE->link=NULL;
         FIRST=NEW_NODE;
      }
      else
      {
         SAVE=FIRST;
         while(SAVE->link!=NULL)
         {
            SAVE=SAVE->link;
         }
         SAVE->link=NEW_NODE;
         NEW_NODE->link=NULL;
      }
      fflush(stdin);
      printf("Enter n for break\n");
      ch=getchar();
   }
}
void search(int x)
{
         int FLAG=0;
         struct node *SAVE;
         if(FIRST==NULL)
         printf("List is Empty. Node Not Found");
         else
         {
         SAVE=FIRST;
         while(SAVE!=NULL)
         {
            if (SAVE->info==x)
            {
            FLAG=1;
            SAVE=SAVE->link;
            }
            else
            {
            SAVE=SAVE->link;
            }
         }
         if(FLAG==1)
         printf("Node Found");
         else
         printf("Node Not Found");
}
}
void display()
{
      struct node *SAVE;
      if(FIRST==NULL)
      {
         printf("Linked List is empty\n");
         return;
      }
      printf("elements are:\n");
      SAVE=FIRST;
      while(SAVE!=NULL)
      {
         if(SAVE->link==NULL)
         printf("|%d|",SAVE->info);
         else
         printf("|%d|->",SAVE->info);
         SAVE=SAVE->link;
      }
      printf("\n");
      return;
}
void main()
{
      int x;
      clrscr();
      FIRST=NULL;
      createlist();
      display();
      printf("Enter value to search");
      scanf("%d",&x);
      search(x);
      getch();
}

Download Projects


Download Programs