This is our first linked list program. A linked list will be created and a specific value from the list will be searched.
# include < stdio.h >
# include < stdlib.h >
struct link
{
char name[100];
char surname[100];
char add[100];
long ph;
struct link *next;
};
int x=0;
struct link *node;
void search(char ch[],struct link *n)
{
node=n - > next;
for(; node != NULL; node = node->next)
{
if(strcmp(node-> name,ch)==0)
{
x++;
printf("Surname is %s \n", node->surname);
printf("Address is %s \n",node-> add);
printf("Phone number is %ld \n",node->ph);
}
}
if(x == 0)
printf("Item not found in the list \n");
}
void get(struct link *n)
{
char ch='y';
node=n;
while(ch !='n')
{
node->next = (struct link* ) malloc (sizeof (struct link));
node = node->next;
node->next =NULL;
printf("\n Enter the name: -");
scanf("%s",node->name);
printf("\n Enter the surname: -");
scanf("%s",node->surname);
printf("\n Enter the address: -");
scanf("%s",node->add);
printf("\n Enter the Telephone number: -");
scanf("%ld",&node->ph);
printf("\n Input choice n for break: ");
ch = getche();
}
}
void main()
{
struct link *start;
char name[15];
clrscr();
start = (struct link* ) malloc (sizeof (struct link));
start->next =NULL;
printf("\n Enter the name: -");
scanf("%s",start->name);
printf("\n Enter the surname: -");
scanf("%s",start->surname);
printf("\n Enter the address: -");
scanf("%s",start->add);
printf("\n Enter the Telephone number: -");
scanf("%ld",&start->ph);
get(start);
printf("\nEnter the name to search :");
scanf("%s",name);
search(name,start);
getch();
}
Technical analysis of this searching program in linked list
As we have discussed in our previous post about the conceptual compartments of a node in data structure, in this program information part variables of the nodes contains number of structure elements like name, surname, address etc. Within the ‘void main () function, the first node of the linked list is created and pointer ‘start’ points the first node of the list. From the main () function the address of the first node of the linked list is passed to user defined function ‘void get (struct tag*)’. While loop is used in this function and a moving pointer of the structure type is used to create the linked list.
From main () function the name to be searched in the linked list is taken and the base address of the list and the name is passed to another function ‘void search ( char [], struct tag*)’. This function use sequential search technique for the purpose of checking in the linked list.
No comments:
Post a Comment