You are on page 1of 2

#include <stdbool.

h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 30

struct Node
{
int data;
char name[MAX];
struct Node *next;
};
struct Node *getUnion(struct Node * , struct Node *);
bool isPresent(struct Node *, int );
void printList(struct Node *);
void push(struct Node **, int ,char []);

int main()
{
int ch,num1,num2;
char name1[MAX]={'\0'} , name2[MAX] = {'\0'};
struct Node *head1 = NULL;
struct Node *head2 = NULL;
struct Node *intersecn = NULL;
struct Node *unin = NULL;
printf("\n enter 1 to insert link list 1, 2 for inserting list 2, 3 to get
their union and 4 to display each list");
do
{
printf("\n enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\n enter the id:");
scanf("%d",&num1);
printf("\n enter the name:");
scanf("%s",name1);
push(&head1,num1,name1);
break;
case 2:
printf("\nenter the id:");
scanf("%d",&num2);
printf("\nenter the name:");
scanf("%s",name2);
push(&head2,num2,name2);
break;
case 3:
unin=getUnion(head1,head2);
printList(unin);
break;
case 4:
printf("\n First list is: ");
printList(head1);
printf("\n Second list is: ");
printList(head2);
break;
}
}while(ch<5);
return 0;
}
struct Node *getUnion(struct Node *head1, struct Node *head2)
{
struct Node *result = NULL;
struct Node *t1 = head1, *t2 = head2;

while (t1 != NULL)


{
push(&result, t1->data,t1->name);
t1 = t1->next;
}

while (t2 != NULL)


{
if (!isPresent(result, t2->data))
push(&result, t2->data,t2->name);
t2 = t2->next;
}

return result;
}
bool isPresent(struct Node *head, int data)
{
struct Node *t = head;
while (t != NULL)
{
if (t->data == data)
return 1;
t = t->next;
}
return 0;
}
void printList(struct Node *node)
{
while (node != NULL)
{
printf(" %d %s ", node->data,node->name);
node = node->next;
}
}
void push(struct Node **head_ref, int new_data,char nm[])
{
struct Node *new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
strcpy(new_node->name,nm);
new_node->next = (*head_ref);
(*head_ref) = new_node;
}

You might also like