Write C program to find intersection between 2 Linked List.

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

//To create structure
struct sll
{
int data;
struct sll *next;
};
typedef struct sll node;

//To define functions
node*create(node*);
node*creates(node*);
void display(node*);
void displays(node*);
void intersection(node*,node*);

void main()
{
int ch;
node*head1=NULL,*head2=NULL;
clrscr();
head1=create(head1);
head2=creates(head2);
printf("\n1st linked list : ");
display(head1);
printf("\n2nd linked list : ");
displays(head2);
printf("\nintersection of list : ");
intersection(head1,head2);
getch();
}

//To create 1st Linked List
node*create(node*head1)
{
node*temp=NULL,*last=NULL;
int n,i;
printf("\nenter how many nodes: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
temp=(node*)malloc(sizeof(node));
printf("\nenter data: ");
scanf("%d",&temp->data);
temp->next=NULL;
if(head1==NULL)
{
head1=temp;
}
else
{
last=head1;
while(last->next!=NULL)
{
last=last->next;
}
last->next=temp;
}
}
return head1;
}

//To create 2nd Linked List
node*creates(node*head2)
{
node*temp=NULL,*last=NULL;
int n,i;
printf("\nenter how many nodes: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
temp=(node*)malloc(sizeof(node));
printf("\nenter data: ");
scanf("%d",&temp->data);
temp->next=NULL;
if(head2==NULL)
{
head2=temp;
}
else
{
last=head2;
while(last->next!=NULL)
{
last=last->next;
}
last->next=temp;
}
}
return head2;
}

//To display elements in 1st Linked List
void display(node*head1)
{
node*last=NULL;
last=head1;
while(last->next!=NULL)
{
printf("%d ",last->data);
last=last->next;
}
printf("%d",last->data);
}

//To display elements in 2nd Linked List
void displays(node*head2)
{
node*last=NULL;
last=head2;

while(last->next!=NULL)
{
printf("%d ",last->data);
last=last->next;
}
printf("%d",last->data);
}

//To find intersection between 2 Linked List.
void intersection(node*head1,node*head2)
{
node*last=NULL,*ptr=NULL,*lasts=NULL,*pt=NULL;
ptr=head2;
while(ptr!=NULL)
{
last=head1;
while(last!=NULL)
{
     if(last->data==ptr->data)
     {
printf("%d ",last->data);

last=last->next;
     }
     else
     {

     last=last->next;
     }
}
ptr=ptr->next;
}
}

0 Comments