#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* next;
};
//Function to insert an element at the end of a linked list
struct node* insert(struct node* head, int data) {
struct node* new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = data;
new_node->next = NULL;
if (head == NULL) {
return new_node;
}
struct node* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = new_node;
return head;
}
//Function to display the elements of a linked list
void print(struct node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
//Function to find the intersection of two linked lists
void intersection(struct node* set1, struct node* set2) {
struct node* current1 = set1;
while (current1 != NULL) {
struct node* current2 = set2;
while (current2 != NULL) {
if (current1->data == current2->data) {
printf("%d ", current1->data);
break;
}
current2 = current2->next;
}
current1 = current1->next;
}
printf("\n");
}
//Function to find the union of two linked lists
void union_set(struct node* set1, struct node* set2) {
struct node* current1 = set1;
while (current1 != NULL) {
printf("%d ", current1->data);
current1 = current1->next;
}
struct node* current2 = set2;
while (current2 != NULL) {
int flag = 0;
current1 = set1;
while (current1 != NULL) {
if (current2->data == current1->data) {
flag = 1;
break;
}
current1 = current1->next;
}
if (flag == 0) {
printf("%d ", current2->data);
}
current2 = current2->next;
}
printf("\n");
}
// Main function
int main() {
struct node* set1 = NULL;
struct node* set2 = NULL;
int size1, size2;
// Get input from the user for the first set
printf("Enter the size of set 1: ");
fflush(stdout);
scanf("%d", &size1);
printf("Enter the elements of set 1: ");
fflush(stdout);
for (int i = 0; i < size1; i++) {
int data;
scanf("%d", &data);
set1 = insert(set1, data);
}
// Get input from the user for the second set
printf("Enter the size of set 2: ");
fflush(stdout);
scanf("%d", &size2);
printf("Enter the elements of set 2: ");
fflush(stdout);
for (int i = 0; i < size2; i++) {
int data;
scanf("%d", &data);
set2 = insert(set2, data);
}
// Find the intersection of the two sets
printf("Intersection: ");
intersection(set1, set2);
// Find the union of the two sets
printf("Union: ");
union_set(set1, set2);
return 0;
}