Facebook

Searching in Linked List

In searching,we find whether the given element is present in the linked list or not.The following program is to search for particular element in linked list.

Program

#include<stdio.h>
struct node
{
    int item;
    struct node *next
};
int main()
{
    struct node *start,*list,*temp;
    int i;
    int num;
    start = (struct node *)malloc(sizeof(struct node));
    list = start;
    start->next = NULL;
    for(i=1;i<5	;i++)
    {   
        list->item = i;
        list->next = (struct node *)malloc(sizeof(struct node));
        list = list->next;
       }
    list->next = NULL;
//printf("Enter the element");
scanf("%d",&num);
temp =start;
 while(temp!=NULL)//Fig2
  {
    if(temp->item == num)
    {
    	printf("%d is present\n",num);
    }
    temp = temp->next;
  }
  printf("Elements of linked lists are:\n");
  while(start != NULL)
    {   
    	if (start->next == NULL) 
    	  {
           break;
    	  }
        printf("%d\n",start->item);
        start = start->next;
    } 
return 0;
}

Run

 

Illustration of Program

  • Refer Linked Lists for creation and display of linked list.
  • temp =start which means temp =140(Fig 1)
  • Say we want to find whether 300 is present in linked list or not.
Screen Shot 2014-04-07 at 1.48.39 PM
Fig 1 : Searching in Linked List
Screen Shot 2014-04-07 at 6.45.25 PM
Fig 2 :Working of Program
Rate this post

Comments

This post currently has one response

Leave a Reply

Your email address will not be published. Required fields are marked *

Sidebar