Monday, 2 April 2012

Program : Singly Linked List - Searching


Program : Singly Linked List - Searching

// Searching in a linked list

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

struct link
{
          int no;
          struct link *next;
};

struct link *node,*start;
int i;

void create_link(struct link *node);
void display(struct link *node);
void search(struct link *node);
void main()
{
          int ch;
          clrscr();
          node=(struct link *)malloc(sizeof(struct link));
          create_link(node);
          printf("\n Output\n");
          display(node);
          search(node);
          getch();
}

void create_link(struct link *node)
{
          char ans;
          i=0;
          start->next=NULL;
          node=start;
          printf("\n Enter 'n' for break:-");
          ans=getchar();
          while(ans!='n')
          {
                   node->next=(struct link *)malloc(sizeof(struct link));
                   node=node->next;
                   printf("\n Enter data for node:-");
                   scanf("%d",&node->no);
                   node->next=NULL;
                   fflush(stdin);
                   printf("\n Enter 'n' for break:-");
                   ans=getchar();
                   i++;
          }
}
void display(struct link *node)
{
          node=start->next;
          while(node)
          {
                   printf("\n  %d",node->no);
                   node=node->next;
          }

}
void search(struct link *node)
{
  int search_node,node_no=1;
  int flag=0;
  node=start->next;
  printf("\n Enter information which you want to search :- ");
          scanf("%d",&search_node);

          while(node)
          {
           if(node->no==search_node)
            {
                   printf("\n Search is successful");
                   printf("\n information %d is found at position d",search_node,node_no);
                   flag=1;
                   break;
            }
            else
            {
                   node=node->next;
            }
            node_no++;
          }
          if(flag==0)
          {
                   printf("\n Information not found");
          }
}

Posted By : Ruchita Pandya

No comments:

Post a Comment