Singly Linked List: Search for key node in the list
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct node
{
int data;
struct node *link;
};
typedef struct node * NODE;
NODE getnode()
{
NODE x;
x = (NODE)malloc(sizeof(struct node));
if(x == NULL)
{
printf("\nInsufficient memory");
exit(0);
}
x->link = NULL;
return x;
}
NODE insert(NODE first)
{
int val;
NODE temp, cur;
temp = getnode();
printf("\nEnter the value: ");
scanf("%d",&val);
temp->data = val;
if(first == NULL)
return temp;
cur = first;
while(cur->link!=NULL)
{
cur = cur->link;
}
cur->link = temp;
return first;
}
void search(NODE first)
{
int key;
NODE cur;
if(first == NULL)
{
printf("\nList is empty");
return;
}
printf("\nEnter the item to be searched: ");
scanf("%d", &key);
cur = first;
while(cur!=NULL)
{
if(cur->data == key)
break;
cur
= cur->link;
}
if(cur == NULL)
printf("\nUnsuccessful search");
else
printf("\nSuccessful search");
}
void display(NODE first)
{
NODE cur;
cur = first;
printf("\nContents are:");
if(cur == NULL)
printf("\nList is empty. Nothing to
display.");
else
{
while(cur!=NULL)
{
printf("|
%d | %d | --> ", cur->data, cur->link);
cur =
cur->link;
}
}
}
void main()
{
int ch, i, n;
NODE first = NULL;
printf("\nEnter number of nodes for list: ");
scanf("%d", &n);
for(i=0;i<n;i++)
first = insert(first);
display(first);
search(first);
}
Output:
Case 1:
Enter number of nodes for list: 4
Enter the value: 11
Enter the value: 12
Enter the value: 13
Enter the value: 14
Contents are:
| 11 | 8722184 | --> | 12 | 8729608 | --> | 13 | 8729624 | -->
| 14 | 0 |
Enter the item to be searched:
12
Successful search
Case 2:
Enter number of nodes for list: 4
Enter the value: 11
Enter the value: 12
Enter the value: 13
Enter the value: 14
Contents are:
| 11 | 7083784 | --> | 12 | 7091208 | --> | 13 | 7091224 | -->
| 14 | 0 |
Enter the item to be searched:
45
Unsuccessful searchAlso Check,