#include <stdio.h>
#include <stdlib.h>
// Linked list node
struct Node {
int data;
struct Node* next;
};
// defining the function
void push(struct Node** head_ref, int new_data);
void printList(struct Node* node);
int isPresent(struct Node* head, int data);
// Function to find union of two linked lists head1 and head2
struct Node* findUnion(struct Node* head1, struct Node* head2)
{
struct Node* result = NULL;
struct Node *x1 = head1, *x2 = head2;
// Insert the elements in list 1
while (x1 != NULL) {
push(&result, x1->data);
x1 = x1->next;
}
// Insert the elements in list 2
while (x2 != NULL) {
if (!isPresent(result, x2->data))
push(&result, x2->data);
x2 = x2->next;
}
return result;
}
// function to find intersection of two lists x1 and x2
struct Node* intersection(struct Node* head1,
struct Node* head2)
{
struct Node* result = NULL;
struct Node* x1 = head1;
while (x1 != NULL) {
if (isPresent(head2, x1->data))
push(&result, x1->data);
x1 = x1->next;
}
return result;
}
// function to insert a node at the beginning of a linked list
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
// function to print a linked list
void printList(struct Node* node)
{
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
// function to check if data is present in linked list
int isPresent(struct Node* head, int data)
{
struct Node* t = head;
while (t != NULL) {
if (t->data == data)
return 1;
t = t->next;
}
return 0;
}
int main()
{
struct Node* head1 = NULL;
struct Node* head2 = NULL;
struct Node* intersecn = NULL;
struct Node* un = NULL;
// Entering x1 list data
push(&head1, 9);
push(&head1, 89);
push(&head1, 7);
push(&head1, 34);
// Entering x2 list data
push(&head2, 89);
push(&head2, 87);
push(&head2, 6);
push(&head2, 7);
intersecn =intersection(head1, head2);
un = findUnion(head1, head2);
printf("\n First list is : ");
printList(head1);
printf("\n Second list is : ");
printList(head2);
printf("\n Intersection list is : ");
printList(intersecn);
printf("\n Union list is : ");
printList(un);
return 0;
}
