Solution:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
};
struct node* head1=NULL;
struct node* head2=NULL;
struct node*intersection=NULL;
struct node* union1=NULL;
void traverse(struct node** head);
struct node* cn()
{
struct node * n;
n=(struct node *)malloc(sizeof(struct node));
return(n);
}
void createnode(struct node **head,int n)
{
int x,i=1;
struct node * newnode,*temp;
printf("Enter elemets for linked list :\n");
for(i=1;i<=n;i++)
{
scanf("%d",&x);
if(*head==NULL)
{
newnode=cn();
newnode->data=x;
newnode->next=NULL;
*head=newnode;
temp=*head;
}
else
{
newnode=cn();
newnode->data=x;
newnode->next=NULL;
temp->next=newnode;
temp=newnode;
}
}
}
void intersection1(int h1, int h2)
{
int i;
struct node *temp1,*temp2,*temp3,*newnode;
temp1=head1;
temp2=head2;
printf("Intersection :\n");
// if(temp1==NULL)
// printf("null");
while(temp1!=NULL)
{
while (temp2!=NULL)
{
if(temp1->data==temp2->data)
{
if(intersection==NULL)
{
newnode=cn();
newnode->data=temp1->data;
newnode->next=NULL;
intersection=newnode;
temp3=intersection;
//printf("%d\n",temp3->data);
}
else
{
newnode=cn();
newnode->data=temp1->data;
newnode->next=NULL;
temp3->next=newnode;
temp3=newnode;
temp3->next=NULL;
}
}
temp2=temp2->next;
}
temp1=temp1->next;
temp2=head2;
}
traverse(&intersection);
}
void union_linkedlist()
{
int i,cnt;
struct node *temp1,*temp2,*temp3,*newnode;
temp1=head1;
temp2=head2;
printf("Union :\n");
while(temp1!=NULL)
{
if(union1==NULL)
{
newnode=cn();
newnode->data=temp1->data;
newnode->next=NULL;
union1=newnode;
temp3=union1;
}
else
{
newnode=cn();
newnode->data=temp1->data;
newnode->next=NULL;
temp3->next=newnode;
temp3=newnode;
temp3->next=NULL;
}
temp1=temp1->next;
}
temp1=head1;
while(temp2!=NULL)
{
cnt=0;
while(temp1!=NULL)
{
if(temp2->data==temp1->data)
{
cnt++;
}
temp1=temp1->next;
}
if(cnt==0)
{
newnode=cn();
newnode->data=temp2->data;
newnode->next=NULL;
temp3->next=newnode;
temp3=newnode;
temp3->next=NULL;
}
temp2=temp2->next;
temp1=head1;
}
traverse(&union1);
}
void traverse(struct node** head) //Function to traverse Linked list.
{
struct node * temp4;
temp4=*head;
while(temp4!=NULL)
{
printf("%d\n",temp4->data);
temp4=temp4->next;
}
}
void main()
{
int h1,h2,choice;
printf("\nEnter size of first linked list :\n");
scanf("%d",&h1);
createnode(&head1,h1);
printf("\nEnter size of second node :\n");
scanf("%d",&h2);
createnode(&head2,h2);
while(choice!=3)
{
printf("\n\n1. Intersection \n");
printf("2. Union \n");
printf("3. Exit \n\n");
scanf("%d",&choice);
switch(choice)
{
case 1: intersection1(h1,h2);
break;
case 2: union_linkedlist(h1,h2);
break;
case 3:exit(0);
break;
}
}
}
0 Comments