write a c program to search an existing element in singly linked list

Solutions on MaxInterview for write a c program to search an existing element in singly linked list by the best coders in the world

showing results for - "write a c program to search an existing element in singly linked list"
Persephone
01 Jun 2019
1#include <stdio.h>
2#include <stdlib.h>
3
4struct node
5{
6  int num;
7  struct node *nextptr;
8}
9 
10stnode, *ennode;
11
12int FindElement(int);
13void main()
14{
15	int n,i,FindElem,FindPlc;
16	stnode.nextptr=NULL;
17	ennode=&stnode;
18		printf("\n\n Linked List : Search an element in a  Singly Linked List :\n");
19		printf("---------------------------------------------------------------\n");
20	
21    printf(" Input the number of nodes : ");
22    scanf("%d", &n);	
23	printf("\n");
24	for(i=0;i< n;i++)
25	{
26		ennode->nextptr=(struct node *)malloc(sizeof(struct node));
27		printf(" Input data for node %d : ",i+1);
28		scanf("%d",&ennode->num);
29		ennode=ennode->nextptr;
30	}
31	ennode->nextptr=NULL;
32	printf("\n Data entered in the list are :\n");
33
34    ennode=&stnode;
35	while(ennode->nextptr!=NULL)
36	{
37		printf(" Data = %d\n",ennode->num);
38		ennode=ennode->nextptr;
39	}
40
41	printf("\n");
42	printf(" Input the element to be searched : ");
43	scanf("%d",&FindElem);
44	FindPlc=FindElement(FindElem);
45	if(FindPlc<=n)
46		printf(" Element found at node %d \n\n",FindPlc);
47	else
48		printf(" This element does not exists in linked list.\n\n");
49}
50int FindElement(int FindElem)
51{
52	int ctr=1;
53	ennode=&stnode;
54	while(ennode->nextptr!=NULL)
55	{
56		if(ennode->num==FindElem)
57			break;
58		else
59			ctr++;
60			ennode=ennode->nextptr;
61	}
62	return ctr;
63}
64
65