Q.) GIVEN TWO SORTED LINK LIST ,FIND THE INTERSECTION NODES OF THE TWO LINK LIST.
example--
list1={2,4,6,7,8}
list2=(1,2,7,10}
output =2,7
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
}*head;
int main()
{
struct node *head1,*head2,*temp1,*temp2;
int num1,num2,i,item;
head1=NULL;
head2=NULL;
printf("\nenter the no. nodes in first list=");
scanf("%d",&num1);
printf("\nenter the elemnts of node one by one\n");
for(i=0;i<num1;i++)
{
scanf("%d",&item);
if(head1==NULL)
{
head1=malloc(sizeof(struct node));
head1->data=item;
temp1=head1;
}
else
{
temp1->next=malloc(sizeof(struct node));
temp1->next->data=item;
temp1=temp1->next;
}
// printf("%d ",temp1->data);
}
temp1->next=NULL;
printf("\nenter the no. of nodes in second list=");
scanf("%d",&num2);
printf("\nenter the elements of node one by one\n");
for(i=0;i<num2;i++)
{
scanf("%d",&item);
if(head2==NULL)
{
head2=malloc(sizeof(struct node));
head2->data=item;
temp2=head2;
}
else
{
temp2->next=malloc(sizeof(struct node));
temp2->next->data=item;
temp2=temp2->next;
}
// printf("%d ",temp2->data);
}
temp2->next=NULL;
temp1=head1;
temp2=head2;
printf("\n intersecting elements of nodes of two given link
list\n");
while(temp1!=NULL&&temp2!=NULL)
{
if(temp1->data==temp2->data)
{
printf("%d ",temp1->data);
temp1=temp1->next;
temp2=temp2->next;
}
else if(temp1->data<temp2->data)
temp1=temp1->next;
else
temp2=temp2->next;
}
return 0;
}
example--
list1={2,4,6,7,8}
list2=(1,2,7,10}
output =2,7
SOLUTION--
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
}*head;
int main()
{
struct node *head1,*head2,*temp1,*temp2;
int num1,num2,i,item;
head1=NULL;
head2=NULL;
printf("\nenter the no. nodes in first list=");
scanf("%d",&num1);
printf("\nenter the elemnts of node one by one\n");
for(i=0;i<num1;i++)
{
scanf("%d",&item);
if(head1==NULL)
{
head1=malloc(sizeof(struct node));
head1->data=item;
temp1=head1;
}
else
{
temp1->next=malloc(sizeof(struct node));
temp1->next->data=item;
temp1=temp1->next;
}
// printf("%d ",temp1->data);
}
temp1->next=NULL;
printf("\nenter the no. of nodes in second list=");
scanf("%d",&num2);
printf("\nenter the elements of node one by one\n");
for(i=0;i<num2;i++)
{
scanf("%d",&item);
if(head2==NULL)
{
head2=malloc(sizeof(struct node));
head2->data=item;
temp2=head2;
}
else
{
temp2->next=malloc(sizeof(struct node));
temp2->next->data=item;
temp2=temp2->next;
}
// printf("%d ",temp2->data);
}
temp2->next=NULL;
temp1=head1;
temp2=head2;
printf("\n intersecting elements of nodes of two given link
list\n");
while(temp1!=NULL&&temp2!=NULL)
{
if(temp1->data==temp2->data)
{
printf("%d ",temp1->data);
temp1=temp1->next;
temp2=temp2->next;
}
else if(temp1->data<temp2->data)
temp1=temp1->next;
else
temp2=temp2->next;
}
return 0;
}
No comments:
Post a Comment