Solution:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node * next;
};
struct node* head=NULL;
struct node *cn()
{
struct node* n;
n=(struct node *)malloc(sizeof(struct node));
return(n);
}
void createnode(int n) //Function to create Linked list.
{
int i,x;
struct node * temp,*newnode;
printf("Enter elements of linked list :\n");
for(i=1;i<=n;i++)
{
scanf("%d",&x);
if(head==NULL) //checking in linked list is empty
{
head=cn();
head->data=x;
head->next=NULL;
temp=head;
}
else
{
newnode=cn();
newnode->data=x;
newnode->next=NULL;
temp->next=newnode;
temp=newnode;
}
}
}
void display() //Function to traverse Linked list.
{
struct node * temp;
temp=head;
while(temp!=NULL)
{
printf("%d\n",temp->data);
temp=temp->next;
}
}
void search(int key) //Function to delete a node from Linked list.
{
struct node * temp;
int i=1,flag=0;
temp=head;
if(head==NULL)
{
printf("Linked list is empty. \n");
}
else
{
while(temp!=NULL)
{
if(key==temp->data)
{
flag=1;
break;
}
temp=temp->next;
i++;
}
}
if(flag==0)
{
printf("Elemet not found.\n");
}
else
{
printf("Element found at position :%d",i);
}
}
void main()
{
int n,key;
printf("Enter size of Linked list :\n");
scanf("%d",&n);
createnode(n);
printf("\n\nLinked List :\n");
display();
printf("\nEnter element you want to search :\n");
scanf("%d",&key);
search(key);
}
0 Comments