F How to search any node location in a single link list? | CodeTheta

How to search any node location in a single link list?

April 17, 2014

/* http://native-code.blogspot.com */

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
typedef struct link
{
int data;
struct link *next;
} node;
node *ins_beg(node*, int);
void display(node*);
int search(node*, int);
void main()
{
int x, n, ch, pos;
node *head=NULL;
while(1)
{
printf("/* http://native-code.blogspot.com */");
printf("\n\n1-->Insert at first\n2-->Display\n3-->Enter value of node to be search\n4-->EXIT\n");
scanf("%d", &ch);
switch(ch)
{
case 1:
printf("Enter data of the node:\n");
scanf("%d", &x);
head=ins_beg(head, x);
break;
case 2:
display(head);
printf("\n");
break;
case 3:
printf("Enter value of node to be search:\n");
scanf("%d", &n);
pos=search(head, n);
if(pos<0)
printf("Node not present in link list");
else
printf("Position is: %d", pos);
printf("\n");
break;
case 4:
exit(0);
default:
printf("\nWrong choice.");
}
}
getch();
}
node *ins_beg(node *h, int x)
{
node *temp, *r=h;
temp=(node*) malloc (sizeof(node));
temp->data=x;
temp->next=NULL;
if(h==NULL)
{
h=temp;
}
else
{
temp->next=h;
h=temp;
}
return(h);
}
void display(node *h)
{
node *r=h;
while(r!=NULL)
{
printf("%d-->", r->data);
r=r->next;
}
printf("NULL");
}
int search(node *h, int k)
{
int pos=1;
node *p=h;
while(p!=NULL)
{
if(p->data==k)
return(pos);
else
pos++;
p=p->next;
}
return(-1);
}

/* http://native-code.blogspot.com */

Post a Comment